• Stars
    star
    403
  • Rank 107,140 (Top 3 %)
  • Language
    Ruby
  • License
    Apache License 2.0
  • Created over 13 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Chef knife plug-in for AWS EC2

Knife EC2

Gem Version Build status

Umbrella Project: Knife

Project State: Active

Issues Response Time Maximum: 14 days

Pull Request Response Time Maximum: 14 days

This is the official Chef Knife plugin for Amazon EC2. This plugin gives knife the ability to create, bootstrap, and manage EC2 instances.

Installation

We highly recommend using Chef Workstation, which includes knife-ec2 out of the box. If for some reason you can't use Chef Workstation you can manually install the gem.

If you're using bundler, simply add Chef and Knife EC2 to your Gemfile:

gem 'knife-ec2'

If you are not using bundler, you can install the gem manually from Rubygems:

$ gem install knife-ec2

Depending on your system's configuration, you may need to run this command with root privileges.

Configuration

In order to communicate with the Amazon's EC2 API you will need to pass Knife your AWS Access Key, Secret Access Key, and if using STS your session token. The knife-ec2 plugin supports multiple methods for configuring these credentials including:

  • AWS configuration / credential files (preferred method)
  • knife.rb / config.rb configuration files
  • environmental variables
  • command line arguments

AWS Configuration / Credential Files

The preferred method of storing credentials for AWS is to use Amazon's own credential and configuration files. The files allow for multiple "profiles", each with their own set of credentials. Also since these credentials aren't stored in your knife.rb/config.rb files you don't have to worry about accidentally checking credentials into a git repository. The configs can be created by hand or generated automatically by running aws configure if the AWS Command Line Interface (awscli) is installed.

See Amazon's Configuration and Credentials Files documentation for additional information on the file format and default locations for Linux/Mac & Windows hosts.

Alternative Config Files Location

If you're not storing the files in their default directory you'll need to specify the location in your knife.rb/config.rb files:

knife[:aws_credential_file] = "/path/to/credentials/file"
knife[:aws_config_file] = "/path/to/configuration/file"

Since the Knife config file is just Ruby you can also avoid hardcoding your home directory, which creates a configuration that can be used for any user:

knife[:aws_credential_file] = File.join(ENV['HOME'], "/.aws/credentials")
knife[:aws_config_file] = File.join(ENV['HOME'], "/path/to/configuration/file")

Specifying the AWS Profile

If you have multiple profiles in your credentials file you can define which profile to use. The default profile will be used if not supplied,

knife[:aws_profile] = "personal"

Config.rb / Knife.rb Configuration

If you prefer to keep all of your configuration in a single location with Chef you can store your Amazon EC2 credentials in Chef's knife.rb or config.rb files:

knife[:aws_access_key_id] = "Your AWS Access Key ID"
knife[:aws_secret_access_key] = "Your AWS Secret Access Key"

Additionally if using AWS STS:

knife[:aws_session_token] = "Your AWS Session Token"

Note: If your knife.rb or config.rb files will be checked into a source control management system, or are otherwise accessible by others, you may want to use one of the other configuration methods to avoid exposing your credentials.

Environmental Variables

Knife-ec2 can also read your credentials from shell environmental variables. Export AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN variables in your shell then add the following configuration to your knife.rb file:

knife[:aws_access_key_id] = ENV['AWS_ACCESS_KEY_ID']
knife[:aws_secret_access_key] = ENV['AWS_SECRET_ACCESS_KEY']

Additionally if using AWS STS:

knife[:aws_session_token] = ENV['AWS_SESSION_TOKEN']

CLI Arguments

You also have the option of passing your AWS API Key/Secret into the individual knife subcommands using the --aws-access-key-id and --aws-secret-access-key command options

Example of provisioning a new t2.micro Ubuntu 16.04 webserver:

$ knife ec2 server create -r 'role[webserver]' -I ami-5e8bb23b -f t2.micro --aws-access-key-id 'Your AWS Access Key ID' --aws-secret-access-key "Your AWS Secret Access Key" -ssh-key my_key_name --region us-west-2

Note: Passing credentials via the command line exposes the credentials in your shell's history and should be avoided unless absolutely necessary.

Additional config.rb & knife.rb Configuration Options

The following configuration options may be set in your configuration file:

  • flavor
  • image
  • availability_zone
  • ssh_key_name
  • aws_session_token
  • region

Using Cloud-Based Secret Data

knife-ec2 now includes the ability to retrieve the encrypted data bag secret and validation keys directly from a cloud-based assets store (currently only S3 is supported). To enable this functionality, you must first upload keys to S3 and give them appropriate permissions. The following is a suggested set of IAM permissions required to make this work:

{
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:Get*",
        "s3:List*"
      ],
      "Resource": [
        "arn:aws:s3:::example.com/chef/*"
      ]
    }
  ]
}

Supported URL format

Use the following configuration options in knife.rb or config.rb to set the source URLs:

knife[:validation_key_url] = 'http://example.com/chef/my-validator.pem'
knife[:s3_secret] = 'http://example.com/chef/encrypted_data_bag_secret'

Alternatively, URLs can be passed directly on the command line:

  • Validation Key: --validation-key-url s3://chef/my-validator.pem
  • Encrypted Data Bag Secret: --s3-secret s3://chef/encrypted_data_bag_secret

knife-ec2 Subcommands

This plugin provides the following Knife subcommands. Specific command options can be found by invoking the subcommand with a --help flag

knife ec2 server create

Provisions a new server in the Amazon EC2 and then perform a Chef bootstrap (using the SSH or WinRM protocols). The goal of the bootstrap is to get Chef installed on the target system so it can run Chef Client with a Chef Server. The main assumption is a baseline OS installation exists (provided by the provisioning). It is primarily intended for Chef Client systems that talk to a Chef server. The examples below create Linux and Windows instances:

# Create some instances -- knife configuration contains the AWS credentials

# A Linux instance via ssh
knife ec2 server create -I ami-d0f89fb9 --ssh-key your-public-key-id -f m1.medium --ssh-user ubuntu --identity-file ~/.ssh/your-private-key

# A Windows instance via the WinRM protocol -- --ssh-key is still required due to EC2 API operations that need it to grant access to the Windows instance
# `--spot-price` option lets you specify the spot pricing
knife ec2 server create -I ami-173d747e -G windows -f m1.medium --user-data ~/your-user-data-file -x '.\a_local_user' -P 'yourpassword' --ssh-key your-public-key-id --spot-price price-in-USD

# Pass --server-connect-attribute to specify the instance attribute that we will try to connect to via ssh/winrm
# Possible values of --server-connect-attribute: private_dns_name, private_ip_address, dns_name, public_ip_address
# If --server-connect-attribute is not specified, knife attempts to determine if connecting to the instance's public or private IP is most appropriate based on other settings
knife ec2 server create -I ami-173d747e -x ubuntu --server-connect-attribute public_ip_address

View additional information on configuring Windows images for bootstrap in the documentation for knife-windows.

Adding server_id to the node name

Users can also include the ec2 server id in the node name by placing %s in the string passed to the --chef-node-name option. The %s is replaced by the ec2 server id dynamically. e.g. -N "www-server-%s" or --chef-node-name "www-server-%s"

Tagging node in Chef

Users can use option --tag-node-in-chef for tagging node in EC2 and chef both with knife ec2 server create command. If user does not pass this option, then the node will be tagged only in EC2.

Tagging EBS Volumes

Users can attach ebs volumes to a new instance being created with knife-ec2 using --volume-tags Tag=Value[,Tag=Value...].

Bootstrap Windows (2012 R2 and above platform) instance without user-data through winrm ssl transport

Users can bootstrap the Windows instance without the need to provide the user-data. knife-ec2 has the ability to bootstrap the Windows instance through winrm protocol using the ssl transport. This requires users to set --winrm-ssl option and --winrm-no-verify-cert. This will do the necessary winrm ssl transport configurations on the target node and the bootstrap will just work.

Note: Users also need to pass the --security-group-ids option with IDs of the security group(s) having the required ports opened like 5986 for winrm ssl transport. In case if --security-group-ids option is not passed then make sure that the default security group in your account has the required ports opened.

Below is the sample command to create a Windows instance and bootstrap it through ssl transport without passing any user-data:

knife ec2 server create -N chef-node-name -I your-windows-image -f flavor-of-server -x '.\a_local_user' -P 'yourpassword' --ssh-key your-public-key-id --winrm-ssl --winrm-no-verify-cert --security-group-ids your-security-groups -VV

Bootstrap Windows (2012 R2 and above platform) instance with user-data through winrm with negotiate transport

Users can bootstrap the Windows instance with the user-data. knife-ec2 has the ability to bootstrap the Windows instance through winrm protocol using the negotiate transport. This requires users to set --winrm-auth-method option as negotiate and --connection-protocol option as winrm and --user-data file. USER DATA file contains winrm configurations which needs to be set for successful winrm communication. This will do the necessary winrm configurations on the target node and the bootstrap will just work.

Note: Users also need to pass the --security-group-ids option with IDs of the security group(s) having the required ports opened like 5985 for winrm with negotiate transport. In case if --security-group-ids option is not passed then make sure that the default security group in your account has the required ports opened.

Below is the sample command to create a Windows instance and bootstrap it through negotiate transport with passing user-data:

knife ec2 server create -N chef-node-name -I your-windows-image -f flavor-of-server -U '.\a_local_user' -P 'yourpassword' --ssh-key your-public-key-id --connection-protocol winrm --winrm-auth-method negotiate --user-data '\path\to\user-data-file' --security-group-ids your-security-groups -VV

Below is the content of user data which is required to set winrm configurations and important ports to get open for successful winrm communication to node.

<powershell>
# Allow script execution
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force
# PS Remoting and & winrm.cmd basic config
Enable-PSRemoting -Force -SkipNetworkProfileCheck
winrm quickconfig -q
$user = "username"
$password = "password"
net user /add $user $password
net localgroup administrators $user /add
winrm create winrm/config/Listener?Address=*+Transport=HTTP
# winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="300"}'
winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="1024"}'
winrm set winrm/config/winrs '@{MaxShellsPerUser="50"}'
winrm set winrm/config '@{MaxTimeoutms="1800000"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
winrm set winrm/config/service/auth '@{Basic="true"}'
netsh advfirewall firewall add rule name="WinRM 5985" protocol=TCP dir=in localport=5985 action=allow
netsh advfirewall firewall add rule name="WinRM 5986" protocol=TCP dir=in localport=5986 action=allow
NetSh Advfirewall set allprofiles state off
net stop winrm
sc.exe config winrm start=auto
net start winrm
</powershell>

Options for bootstrapping Windows

The knife ec2 server create command also supports the following options for bootstrapping a Windows node after the VM is created:

:connection_password           The WinRM password
:winrm_auth_method             Defaults to negotiate, supports kerberos, can be set to basic for debugging
:winrm_ssl                     SSL in the WinRM connection
:connection_port               Defaults to 5985 plaintext transport, or 5986 for SSL
:ca_trust_file                 The CA certificate file to use to verify the server when using SSL
:winrm_no_verify_cert          When flag is present, SSL cert will not be verified. Same as original mode of 'verify_none'
:kerberos_keytab_file          The Kerberos keytab file used for authentication
:kerberos_realm                The Kerberos realm used for authentication
:kerberos_service              The Kerberos service used for authentication

knife ec2 ami list

This command provides the feature to list all EC2 AMIs. It also provides the feature to filter the AMIs based on owner and platform.

knife ec2 ami list

Options for AMIs list

  • Owner: By default owner is aws-marketplace but you can specify following owner with the help of -o or --owner:

    command: knife ec2 ami list -o (options)

    :self                         Displays the list of AMIs created by the user.
    :aws-marketplace              Displays all AMIs form trusted vendors like Ubuntu, Microsoft, SAP, Zend as well as many open source offering.
    :micosoft                     Displays only Microsoft vendor AMIs.
    
  • Platform: By default all platform AMIs are displayed, but you can filter your response by specifying the platform using -p or --platform:

    command: knife ec2 ami list -p (options)

    :Allowed platform             windows, ubuntu, debian, centos, fedora, rhel, nginx, turnkey, jumpbox, coreos, cisco, amazon, nessus
    
  • Search: User can search any string into the description column by using -s or --search:

    command: knife ec2 ami list -s (search_keyword)

    :search_keyword             Any String or number
    

knife ec2 server list

Outputs a list of all servers in the currently configured AWS account. Note, this shows all instances associated with the account, some of which may not be currently managed by the Chef server.

knife ec2 server delete

Deletes an existing server in the currently configured AWS account. By default, this does not delete the associated node and client objects from the Chef server. To do so, add the --purge flag

Development Documentation

All documentation is written using YARD. You can generate a by running:

rake docs

Contributing

For information on contributing to this project please see our Contributing Documentation

License & Copyright

  • Copyright:: Copyright (c) 2009-2019 Chef Software, Inc.
  • License:: Apache License, Version 2.0
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

    http://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.

More Repositories

1

chef

Chef Infra, a powerful automation platform that transforms infrastructure into code automating how infrastructure is configured, deployed and managed across any environment, at any scale
Ruby
7,596
star
2

bento

Packer templates for building minimal Vagrant baseboxes for multiple platforms
HCL
4,220
star
3

omnibus

Easily create full-stack installers for your project across a variety of platforms.
Ruby
1,269
star
4

ohai

Ohai profiles your system and emits JSON
Ruby
672
star
5

chef-zero

Simple, easy-run, fast-start in-memory Chef server for testing and solo purposes
Ruby
534
star
6

chef-vault

Securely manage passwords, certs, and other secrets in Chef
Ruby
407
star
7

chef-server

Chef Infra Server is a hub for configuration data; storing cookbooks, node policies and metadata of managed nodes.
Erlang
279
star
8

automate

Chef Automate provides a full suite of enterprise capabilities for maintaining continuous visibility into application, infrastructure, and security automation.
Go
227
star
9

supermarket

Chef's community platform
Ruby
214
star
10

knife-vsphere

Chef knife plug-in for VMware vSphere
Ruby
202
star
11

knife-windows

Plugin for Chef's knife tool for working with Windows nodes
Ruby
151
star
12

omnibus-software

Open Source Software for use in Omnibus built packages
Ruby
133
star
13

chef-workstation

Chef Workstation gives you everything you need to get started with Chef, so you can automate how you audit, configure, and manage applications end environments.
Go
133
star
14

mixlib-shellout

mixin library for subprocess management, output collection
Ruby
132
star
15

chef-web-docs

All The Documentation
HTML
127
star
16

mixlib-cli

A mixin for creating command line applications - gives an easy DSL for argument specification and processing
Ruby
123
star
17

knife-openstack

Chef Infra knife plug-in for OpenStack
Ruby
120
star
18

cookstyle

A linting tool that helps you to write better Chef Infra cookbooks and InSpec profiles by detecting and automatically correcting style, syntax, and logic mistakes in your code.
Ruby
109
star
19

os_release

A repo containing the /etc/os-release file from various Linux distros
81
star
20

chef-oss-practices

Documentation and Practices for Open Source Development at Chef
Ruby
81
star
21

knife-azure

Chef knife plug-in for Microsoft Azure
Ruby
72
star
22

artifactory-client

A simple, lightweight Ruby client for interacting with the Artifactory API.
Ruby
68
star
23

knife-google

Chef knife plug-in for Google Compute
Ruby
67
star
24

win32-service

A Ruby library that allows users to inspect, control or create services on MS Windows
Ruby
65
star
25

mixer

Mix in functions from other modules
Erlang
64
star
26

concrete

Concrete enhances your rebar based Erlang project by providing a common Makefile wrapper, a dialyzer make target that caches PLT analysis of your project's dependencies, and a mechanism to specify development only dependencies.
Erlang
56
star
27

mixlib-config

A simple class based Config mechanism, similar to the one found in Chef
Ruby
51
star
28

sqerl

General purpose RDBMS abstraction layer
Erlang
42
star
29

vscode-chef

Chef Infra Extension for Visual Studio Code
TypeScript
39
star
30

cheffish

Resources and tools for testing and interacting with Chef and Chef Server.
Ruby
39
star
31

knife-tidy

Report on stale Chef Server nodes/cookbooks, clean those up and additionally clean data integrity issues from a knife-ec-backup object based backup!
Ruby
37
star
32

homebrew-chef

A homebrew tap for ChefDK, Workstation, and InSpec
Ruby
36
star
33

mixlib-log

A simple class based Log mechanism, similar to Merb and Chef, that you can mix in to your project.
Ruby
34
star
34

effortless

Automated best practices for Chef Infra and Chef InSpec
Shell
33
star
35

chef-load

chef-load - a tool for simulating load on a Chef Infra Server and/or a Chef Automate server
Roff
32
star
36

knife-ec-backup

Backup and restore Chef Infra Server in a repository-compatible format
Ruby
31
star
37

mini_s3

Minimal AWS S3 client for Erlang
Erlang
28
star
38

okta_aws

Tool for accessing the AWS API for an account you normally access via okta
Python
27
star
39

dep-selector

Fast Dependency Solver for Ruby using Gecode
Ruby
25
star
40

omnitruck

Web service to automate the release of Omnibus artifacts
Ruby
25
star
41

win32-process

A Ruby library that adds or redefines several methods for the Process module
Ruby
25
star
42

kitchen-vcenter

A test-kitchen driver for vCenter REST API
Ruby
25
star
43

omnibus-ctl

Provides service control for omnibus packages
Ruby
23
star
44

mixlib-authentication

AuthN signing and verification. Appears in both the client and server
Ruby
22
star
45

knife-cloud

Library for Chef knife cloud plugins
Ruby
18
star
46

win32-taskscheduler

A Ruby interface for the task scheduler on MS Windows
Ruby
17
star
47

mixlib-versioning

General purpose Ruby library that allows you to parse, compare, and manipulate version strings in multiple formats.
Ruby
17
star
48

win32-eventlog

The win32-eventlog library provides a Ruby interface for reading from and writing to the Windows Event Log
Ruby
17
star
49

chefstyle

Version Pinned RuboCop with Chef approved Cop list for linting software - NOT FOR COOKBOOKS
Ruby
15
star
50

chef-cli

The 'chef' command line tool included in Chef Workstation
Ruby
14
star
51

win32-file

Extra methods, and redefined methods, for the File class on MS Windows
Ruby
14
star
52

anka-buildkite-plugin

Run Buildkite steps inside Veertu Anka Virtual Machines
Shell
14
star
53

appbundler

Generate locked binstubs for ruby applications
Ruby
14
star
54

stats_hero

General purpose stats collection
Erlang
13
star
55

wmi-lite

Lightweight, low-dependency wrapper for basic WMI functionality on Windows.
Ruby
13
star
56

knife-vrealize

Plugin for Chef's knife tool to interact with VMware vRealize products
Ruby
13
star
57

chef-apply

The ad-hoc execution tool for the Chef ecosystem.
Ruby
13
star
58

ffi-libarchive

A Ruby FFI binding to libarchive.
Ruby
13
star
59

mixlib-install

A library for interacting with Chef Software Inc's software distribution systems.
Ruby
12
star
60

chef_authn

Erlang API request authentication signing and verification for Chef
Erlang
11
star
61

ffi-yajl

Ruby FFI gem wrapper around yajl2 library
Ruby
11
star
62

corefoundation

FFI based Ruby bindings for the CoreFoundation frameworks
Ruby
11
star
63

fixie

Low level manipulation tool for chef in sql
Ruby
10
star
64

dep-selector-libgecode

Bundled Gecode Libraries for dep-selector
Ruby
10
star
65

win32-certstore

Ruby library for accessing the certificate store on Windows
Ruby
10
star
66

chef-workstation-app

The Chef Workstation desktop application.
TypeScript
10
star
67

win32-security

A Ruby interface for security aspects of MS Windows
Ruby
9
star
68

knife-vcenter

Chef knife plug-in for VMware REST API
Ruby
9
star
69

architecture-center

Ruby
9
star
70

win32-dir

A series of constants, and extra or redefined methods, for the Dir class on Windows
Ruby
8
star
71

chef_backup

A library to backup an Chef server
Ruby
8
star
72

chef-vault-testfixtures

provides an RSpec shared context for testing Chef cookbooks that use chef-vault
Ruby
7
star
73

opscoderl_httpc

Opscode helper application for being an HTTP client
Erlang
7
star
74

license-acceptance

Chef Software libraries for accepting usage license
Ruby
7
star
75

rubydistros

Dockerfiles for Ruby on various Linux distros
Dockerfile
7
star
76

win32-mmap

A Ruby interface for memory mapped files on MS Windows
Ruby
7
star
77

chef-analyze

A CLI to analyze artifacts from a Chef Infra Server
Go
6
star
78

win32-event

A Ruby interface to Event objects on MS Windows
Ruby
6
star
79

license_scout

Discovers license information of the dependencies of a project.
Ruby
6
star
80

.github

.github files that are inherited by all org repos unless specifically included in a repo
6
star
81

cookbook-omnifetch

Fetch Chef Cookbooks from Various Sources to a Local Cache
Ruby
6
star
82

win32-ipc

A Ruby abstract base class for synchronization objects on MS Windows
Ruby
5
star
83

github-workflows

Github Actions Workflows
5
star
84

appbundle-updater

A little help when you want to update an appbundled project inside of a Chef/ChefDK omnibus package
Ruby
5
star
85

ci-studio-common

Shared helpers for use inside CIs (like Travis) and a Habitat Studio
Go
5
star
86

omnibus-toolchain

Omnibus packaging for Omnibus toolchain
Ruby
5
star
87

chef-web-core

Shared resources for Chef web properties
Ruby
5
star
88

gatherlogs-reporter

Inspec profiles for examining gatherlog output from chef-products for support.
Ruby
5
star
89

chocolatey-packages

PowerShell
4
star
90

compliance-workshop-environment

Ruby
4
star
91

inspec-extra-resources

Ruby
4
star
92

folsom_graphite

Send data from folsom automatically to graphite
Erlang
4
star
93

chef-powershell-shim

.NET 4.0/COM wrapper around PowerShell host
Ruby
4
star
94

cookstylist

Cookstyle GitHub app
Ruby
4
star
95

automate-liveness-agent

Agent that sends "keep alive" messages to Chef Automate
Ruby
4
star
96

community_cookbook_releaser

A simple script to aid in version bumps and changelog generation for Chef managed community cookbooks
Ruby
4
star
97

habitat_exporter

Go
4
star
98

mixlib-archive

A very simple gem to create and extract archives.
Ruby
4
star
99

win32-mutex

A Ruby interface for mutexes on MS Windows
Ruby
3
star
100

chef_dictionary

A dictionary file of words in the Chef ecosystem
Ruby
3
star