Amazon provides a nice little script in their documentation, that can be used to associate an EC2 instance with a Chef server (for example AWS OpsWorks for Chef Automate) from userdata.
This is great if you want to apply Chef recipes to instances launched by an autoscaling group and you want to avoid prebaking the AMIs with chef installed. By handling the chef-client install and server association from userdata, you can use the default AMIs. Knife does support launching and bootstrapping ec2 instances, but this can't be used for autoscaling groups as they are launched automatically and needs to be bootstrapped unattended.
Unfortunately Amazon only provides a bash version and since I had a need to use Chef on Windows instances, I re-implemented the functionality with Powershell.
UPDATE 2017-11-06: AWS now includes a userdata.ps1 with the starterkit you can download from OpsWorks.
The basic steps goes like this:
- Install OpenSSL
- Install Chef
- Associate the node with the Chef Server
- Run chef-client with an optional run-list
Step 1. actually proved to be the most difficult. OpenSSL is not usually readily available on Windows instances and OpenSSL.org does not provide an official binary. I opted to use the binaries from slproweb.com but you may change that to your preference.
AWS only executes userdata automatically on the initial boot of a new instance, so subsequent boots won't attempt to re-associate the node.
Get the script at: https://github.com/brianlund/bootstrap-windows-chef-node
Wrap it in <powershell></powershell> tags and add it to userdata when launching an instance, either from the AWS console, an autoscaling launch configuration or cloudformation. Refer to the AWS docs for detailed instructions on how to use userdata.