Skip to content

Instantly share code, notes, and snippets.

@supercede
Last active August 2, 2022 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save supercede/a88757803ce8b1744a8d00c567fdbdbe to your computer and use it in GitHub Desktop.
Save supercede/a88757803ce8b1744a8d00c567fdbdbe to your computer and use it in GitHub Desktop.
AWS Cloudformation User Data script in install nodejs, pm2, codedeploy agent and set env variables from AWS parameter store (or AWS secrets manager if you tweak the aws command). AWS Parameter Store uses parameter hierarchies to organize and manage parameter access in an easier manner.
UserData:
"Fn::Base64": !Sub |
#!/bin/bash
yum install ruby -y
wget https://aws-codedeploy-${AWS::Region}.s3.${AWS::Region}.amazonaws.com/latest/install
chmod +x ./install
./install auto
cd /tmp
yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm
systemctl enable amazon-ssm-agent
systemctl start amazon-ssm-agent
cat > /tmp/subscript.sh << EOF
# START
echo "Setting up NodeJS Environment"
curl https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion
# Dot source the files to ensure that variables are available within the current shell
. /home/ec2-user/.nvm/nvm.sh
. /home/ec2-user/.bashrc
# Install NVM, NPM, Node.JS & CodeDeployAgent
nvm install v16.15.0
nvm alias default v16.15.0
nvm use v16.15.0
npm i -g pm2
# Set Env vars
echo 'export KEY_1=$(aws ssm get-parameter --name "/hierarchy/KEY_1" --region us-east-2 --query Parameter.Value --with-decryption)' >> /home/ec2-user/.bashrc
echo 'export KEY_2=$(aws ssm get-parameter --name "/hierarchy/KEY_2" --region us-east-2 --query Parameter.Value --with-decryption)' >> /home/ec2-user/.bashrc
echo 'export KEY_3=$(aws ssm get-parameter --name "/hierarchy/KEY_3" --region us-east-2 --query Parameter.Value --with-decryption)' >> /home/ec2-user/.bashrc
EOF
chown ec2-user:ec2-user /tmp/subscript.sh && chmod a+x /tmp/subscript.sh
sleep 1; su - ec2-user -c "/tmp/subscript.sh"
@supercede
Copy link
Author

The instance above is an Amazon Linux 2 instance; yum is the package manager while ec2-user is the default user. Use the suitable values for your EC2 instance type.

You can start from yum install ruby -y if not using cloudformation

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment