Skip to content

Instantly share code, notes, and snippets.

@miere
Created May 12, 2019 00:55
Show Gist options
  • Select an option

  • Save miere/68e06cff4881d93d5e460067a0eb1bdf to your computer and use it in GitHub Desktop.

Select an option

Save miere/68e06cff4881d93d5e460067a0eb1bdf to your computer and use it in GitHub Desktop.
AWS User Data script to configure CloudWatch Log Agent, Code Deploy agent and basic java 8 installation.
#!/usr/bin/env bash
# Configures an Amazon Linux instance. It includes:
# - to have its logs automatically sent to CloudWatch
# - pre-configured with Python, Ruby and Java runtime environment
# - CodeDeploy agent up and running expecting for deployment tasks
# VARIABLES
INSTANCE_ID=`/usr/bin/curl -s http://169.254.169.254/latest/meta-data/instance-id`
URL_CODE_DEPLOY=https://aws-codedeploy-${region}.s3.amazonaws.com/latest/codedeploy-agent.noarch.rpm
URL_CORRETTO=https://d1f2yzg3dx5xke.cloudfront.net/java-1.8.0-amazon-corretto-1.8.0_202.b08-1.amzn2.x86_64.rpm
# MAIN
mkdir -p /opt
# Configuring Swap Files
dd if=/dev/zero of=/swapfile bs=1G count=2
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile swap swap defaults 0 0' >> /etc/fstab
# Installing base packages
yum update -y
yum install -y awslogs ruby
# Installing AWS Corretto JRE 8
curl $URL_CORRETTO -o java8.rpm
yum install -y java8.rpm
# Setting up CloudWatch Agent
sed -i -e 's/us-east-1/${region}/g' /etc/awslogs/awscli.conf
cat <<EOF > /etc/awslogs/awslogs.conf
[general]
state_file = /var/lib/awslogs/agent-state
use_gzip_http_content_encoding = true
[/var/log/messages]
log_group_name = ${log_group_name}
log_stream_name = /ec2/{instance_id}/var/log/messages
file = /var/log/messages
datetime_format = %Y-%m-%d %H:%M:%S
buffer_duration = 5000
initial_position = start_of_file
[/opt/application/server.log]
log_group_name = ${log_group_name}
log_stream_name = /ec2/{instance_id}/opt/application/server.log
file = /opt/application/server.log
datetime_format = %Y-%m-%d %H:%M:%S
initial_position = start_of_file
time_zone = UTC
encoding = utf_8
buffer_duration = 5000
EOF
systemctl start awslogsd
systemctl enable awslogsd.service
# Setting up CodeDeploy agent
curl $URL_CODE_DEPLOY --output codedeploy-agent.noarch.rpm
yum install -y codedeploy-agent.noarch.rpm
service codedeploy-agent start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment