I was under the impression that all Amazon EC2 instances have the latest version of AWS CLI installed. So, I was in for a shock when I discovered that is not always the case. However, I was required to use the AWS CLI, and since this was an Amazon EC2 with Windows OS, I proceeded with installing the AWS.Tools module for PowerShell. I automated the installation with the Amazon EC2 user data script and Terraform. If you are interested in the steps to install AWS CLI on an Amazon EC2 instance using the user data script, check this note - Install AWS CLI on an Amazon EC2 instance using Terraform and user data. Note: I wrote this note as part of a series on Amazon EC2 user data script. However, reading all the earlier notes is unnecessary if you are interested ONLY in the steps involved in installing AWS.Tools module for PowerShell on Amazon EC2. But it won’t hurt to read the other notes if you want to get the complete picture and maybe learn something new. I have the links to the other articles in the GitHub repository.

If you are new to the Amazon EC2 user data script, I have a separate note to discuss the steps to start using the user data script  -working with Amazon EC2 user data and Terraform.

User data could be set to run only once when the Amazon EC2 instance is provisioned or multiple times with each restart. That is managed via the <persist> flag in the user data script. I prefer having the flag set to <persist>true</persist> since specific provisioning requirements involve restarts. That implies that the user data script needs to be idempotent -run as many times, but the end state is the same.

To install AWS.Tools module for PowerShell, I also required the NuGet package to be installed, which had to be idempotent. So the algorithm was: Step 1: Get a list of all the modules installed. Step 2: Check if the AWS.Tools.Installer module exists. Step 3: Exit out if the module exists since the desired state exists. Else, move to Step 4. Step 4: Check the list of packages installed since the AWS.Tools.Installer module requires NuGet package version 2.8.5.201 or above. Step 5: If the correct version of the NuGet package is installed, move to Step 6. Otherwise, install the correct version of the package. Step 6: Install the AWS.Tools.Installer module.

I converted the logic associated with the algorithm in the user data script(user_data\user_data.tpl) and stored it in my Github repo: add-aws.tools-powershell-to-userdata

And that is how I installed the AWS.Tools module and ran a few AWS CLI commands from the Amazon EC2 instance. If you want to know more, I have two more related notes on the user data script that may interest you: How to attach an IAM role to an Amazon EC2 instance and how to manage sensitive variables in the user data script.

I hope you found this note useful. Please do not hesitate to reach out with your suggestions or comments.