Automate New Relic Agent Integration with Java

Sravan K
2 min readApr 10, 2020

Hey Net-Heads!!
Isn’t it true that the machines have taken over the world. And this post is about the machines that can automate the process by running few lines of code.

Let’s implement scripts to install New relic agent on tomcat server and pass user data to the EC2 instance that can be used to run scripts after the instance starts.

OH, Wait!!! Before We Start

To understand the approach in integrating New Relic Java agent with Monolithic Java Applications, you can refer to:

Scripting…

Keep Calm And Automate

Terraform template file:

Let’s create a user data template file aws-user-data.tpl and include the commands to be executed at the instance launch time.

# Create a directory for New Relic within tomcat directory
cd /usr/share/tomcat/
mkdir newrelic
sudo chown -R tomcat:tomcat newrelic
# Download New Relic files
wget https://download.newrelic.com/newrelic/java-agent/newrelic-agent/current/newrelic-java.zip
# Unzip the newrelic-java.zip
unzip newrelic-java.zip # unzips to newrelic folder
rm -rf newrelic-java.zip
# Copy newrelic.jar and newrelic.yml
cp newrelic/newrelic.jar /usr/share/tomcat/newrelic/
cp newrelic/newrelic.yml /usr/share/tomcat/newrelic/
rm -rf newrelic
# Change mode and owner
sudo chmod 655 /usr/share/tomcat/newrelic/*
sudo chown -R tomcat:tomcat /usr/share/tomcat/newrelic/*
# Get New Relic license from AWS parameter store
NEWRELIC_LICENSE_KEY=$(aws ssm get-parameter --region=eu-west-1 --name=NEWRELIC_LICENSE --with-decryption --query=Parameter.Value --output text)
# Write New Relic ENV variables to setenv.sh
echo "export NEW_RELIC_APP_NAME=sherlock-holmes" >> /usr/share/tomcat/bin/setenv.sh
echo "export NEW_RELIC_LICENSE_KEY=$${NEWRELIC_LICENSE_KEY}" >> /usr/share/tomcat/bin/setenv.sh# Write JAVA_OPTS to setenv.sh
echo -e "JAVA_OPTS=\"\$JAVA_OPTS -javaagent:/usr/share/tomcat/newrelic/newrelic.jar -Dnewrelic.environment=${environment}\"" >> /usr/share/tomcat/bin/setenv.sh
# Change mode and owner
sudo chmod 655 /usr/share/tomcat/bin/setenv.sh
sudo chown -R tomcat:tomcat /usr/share/tomcat/bin/setenv.sh

You can pass the aws-user-data.tpl file as user_data to AWS Launch Configuration resource

resource "aws_launch_configuration" "sherlock_launch_configuration"{
/* setting other variables */
user_data = file("${path.module}/aws-user-data.tpl")
}

Now, the user data will run the script and provision New Relic Java agent, every time the instance is launched.

Thank you for reading!!
Stay tuned for more productionised solutions!!!

Happy Coding!!!

Interested to read more stories, you can find my writings here:

--

--

Sravan K
Sravan K

No responses yet