In the last post, I discussed the steps involved in installing AWS.Tools module for PowerShell on Amazon EC2 using user data and Terraform. This post lists the steps to install the AWS CLI on an Windows Amazon EC2 instance.
I used Amazon EC2 user data and Terraform to automate AWS CLI installation as part of the Amazon EC2 provisioning process. Moreover, I prefer to have the user data script be persistent (starts each time after a machine restart). Hence, all the functions within the user data script must be idempotent, including the AWS CLI installation.
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.
To install AWS CLI and to make the process idempotent, I classified it into the following steps:
Step 1: Check if AWS CLI was installed. If installed, do nothing.
The idea behind this step is due to the need to create idempotent scripts. If the desired end state (AWS CLI installed) is achieved, do not download the installer or proceed with the installation.
Step 2: If AWS CLI is not installed, install the latest version and restart the Amazon EC2 instance.
I first downloaded the installer and then used the PowerShell Start-Process
block with the -Wait
flag to install the CLI. After that, I set the flag value InstallAWSFlag.txt
to true
. A machine restart followed this. If you wonder about the need to restart the Amazon EC2 instance, there is no need. You see, as part of successful install verification, I could not identify a method to check for the AWS CLI version right after the installation since the PowerShell instance does not have the environment variables updated. A new PowerShell instance would have that, but I could not find a way to manage that using the user data script. A quicker approach was to trigger a machine restart which caused the user data script to rerun, and the condition under Step 1 was fulfilled.
I applied 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-cli-to-userdata.
Here is an image from the user data log file generated by the user data script when Terraform provisioned the Amazon EC2 instance and after each restart.
As you can see, the identification of the AWS CLI version took place after a machine restart.
And that is how I installed the AWS CLI 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 you will find interesting – 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 suggestion or comments.
2 thoughts on “Install AWS CLI on a Windows Amazon EC2 instance using Terraform and user data”