autozane terraform

Automating AWS CloudWatch Logs on Ubuntu

The AWS CloudWatch Logs service acts like a Logstash agent on your EC2 instances. It can be configured to capture log entires and send them to CloudWatch. There are a lot of different customization options with AWS CloudWatch Logs, such as how to format log entries, log group names, etc. In this post we will automate the installation of AWS CloudWatch Logs on an Ubuntu instance using PackerIO. The example service that we will capture logs for will be an Aptly API server. PackerIO will automate the installation and configuration of the service for us, and Terraform will be used to configure the IAM Role and Instance Profile we will need to be able to interact with CloudWatch and Log services on AWS. This is a working deployment strategy for Aptly server here. We will just focus on the awslogs agent install and required Terraform.

Let's start with the PackerIO configurations required to make this work.

Under the provisioner section lets download and install the awslogs agent.

  "provisioners": [
      "type"   : "shell",
      "inline" : [
        "sudo apt-get update",
        "sudo apt-get -y install curl python software-properties-common xz-utils bzip2 gnupg wget graphviz",
        "sudo wget -O /tmp/",
        "sudo chmod 775 /tmp/",
        "sudo mkdir -p /var/awslogs/etc/"

Next, let's call out an awslogs.conf file that is local to the PackerIO configuration that we can use with the PackerIO file provisioner.

      "type"        : "file",
      "source"      : "awslogs/awslogs.conf.aptly",
      "destination" : "/var/awslogs/etc/awslogs.conf.packer"

The final setup on the PackerIO side is to run a privileged Shell provisioner to perform a no-prompt install of awslogs and call use our awslogs.conf file that will pull in the logs of our Aptly API service.

      "type"   : "shell",
      "inline" : [
        "sudo python /tmp/ --region=us-west-2 --non-interactive -c /var/awslogs/etc/awslogs.conf.packer",
        "mv /tmp/aptly.service /etc/systemd/system/aptly.service",
        "mv /tmp/aptly.conf /etc/aptly.conf",
        "echo 'deb squeeze main' > /etc/apt/sources.list.d/aptly.list",
        "apt-key adv --keyserver --recv-keys 2A194991",
        "apt-get update",
        "apt-get install aptly -y --force-yes",
        "touch /var/log/aptly-api.log",
        "sudo systemctl daemon-reload",
        "sudo systemctl enable awslogs",
        "sudo systemctl enable aptly"
      "execute_command" : "echo 'packer' | {{ .Vars }} sudo -E -S sh '{{ .Path }}'"

The above shell provisioner configues awslogs to run on boot, and also our example Aptly API service which we will be forwarding logs for.

Let's run PackerIO from our Jenkins CI and save this AMI.

Now that we have a PackerIO built AMI we can promote some Terraform that will use the latest AMI based upon a name search. In our PackerIO configuration we saved the AMI with a name "aptly-{timestamp}". In Terraform we can call out the latest based upon this AMI. We are leveraging the new AMI data source here.

data "aws_ami" "aptly" {
  most_recent = true

  filter {
    name   = "name"
    values = ["aptly-*"]

  owners = ["self"]

Our Terraform will apply the appropriate IAM Instance Profile to grant awslogs agent access to write logs into CloudWatch and to create log groups.

resource "aws_iam_instance_profile" "aptly_instance_profile" {
  name  = "aptly-instance-profile"
  roles = ["${}"]

resource "aws_iam_role" "aptly_role" {
  name = "aptly-role"

  assume_role_policy = <<EOF
  "Version": "2012-10-17",
  "Statement": [
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": ""
      "Effect": "Allow",
      "Sid": ""

resource "aws_iam_policy" "CloudWatchAccess" {
  name        = "CloudWatchAccess-aptly"
  description = "CloudWatch Access"

  policy = <<EOF
    "Version": "2012-10-17",
    "Statement": [
            "Effect": "Allow",
            "Action": [
            "Resource": [

resource "aws_iam_policy_attachment" "attach_cloudwatch" {
  name       = "aptly-iam-attachment"
  policy_arn = "${aws_iam_policy.CloudWatchAccess.arn}"
  roles      = ["${}"]

Let's apply promote this get an EC2 instance running using Terraform and then validate that logs are coming into CloudWatch for the Aptly API server.

Great! With that instance running, let's confirm that we have logs coming into AWS CloudWatch now.

In this post we were able to dial in automated installation of AWS CloudWatch Logs (awslogs agent) with PackerIO and then used Terraform to create the required IAM Instance Profile that is attached to the instance. This Instance Profile gave the ec2 instance running our example service (Aptly API) and awslogs agent access to CloudWatch to create a Log Group and start sending logs to it.

Supporting PackerIO and Terraform Code Examples:

Managing Terraform Versions on Jenkins

When leveraging Terraform to code your infrastructure you will notice that the release cadence for new versions of Terraform is fast. In this post I will show you how to manage upgrading versions of Terraform on a per Jenkins Job basis. This will allow you to run multiple versions of Terraform on your Jenkins system and gives you the flexibility to control when to upgrade a given Terraform state to a newer version of Terraform.

We will be leveraging this great open source wrapper: tfenv. Thank you kamatam41 for sharing this.

To get this installed on a Jenkins system I have provide a small Chef snippet for this:

This will setup a couple versions of Terraform for our job to work with. Here is the example Jenkins Terraform job. We will leverage some Terraform code I put on Github that will create an AWS S3 bucket, a S3 bucket policy to attach to the S3 bucket, and an AWS VPC.

I want to leverage a new Terraform AWS resource provider new to 0.7.3 called aws_s3_bucket_policy. We add it to our Terraform code example, seen here.

Let's first try to 'plan' this Terraform code using 0.7.2. With this version we should expect to see a failure to plan since the aws_s3_bucket_policy resource isn't available in this version. We can control the version we want to use for Terraform with the hidden file .terraform-version in our configuration directory where we run Terraform.

Note we see the failure:

aws_s3_bucket_policy.autozane_s3_policy: Provider doesn't support resource: aws_s3_bucket_policy

Ok, now let's commit a change to our .terraform-version file and call out the usage of 0.7.3 for this state. We should see now see a successful 'plan' that will include the creation of the requested AWS resources (S3 bucket, S3 Bucket Policy, VPC).

Success! We were able to leverage tfenv inside of our Jenkins CI environment to upgrade to a newer version of Terraform. This upgrade didn't affect any other Terraform jobs on this Jenkins system that were perhaps using other Terraform versions.

Example Terraform and Jenkins config

tfenv on Github

Chef to install tfenv on Jenkins

Terraform Recipe: Continuous Integration on Amazon Web Services

Most Terraform use cases involve relatively static infrastructure. In this recipe I will explore a more dynamic use case. Here we will leverage Terraform to run a continuous code integration into Amazon Web Services (AWS). Below I will provide a visual of what is achieved, followed up with a description of each step in what I call the "Infrastructure Time Line".

  1. We start off with a code release that is already running in an ASG from a previous deployment. This is referenced as Amazon Machine Image-x (AMI-x).

  2. Provision your new code in a new AMI via PackerIO (I will cover this specific step in a future post, stay tuned). The resulting AMI is referred to as AMI-y. We then pass AMI-y as a variable to Terraform. Terraform is then leveraged to deploy a new Autoscaling Group (ASG) to run along side the current running ASG (Using AMI-y).

  3. Terraform waits for successful provisioning of the new ASG. The ASG is configured to use EC2 health checks since we are not leveraging an ELB in this use case. We will rely on a watchdog script to report to the instance's autoscaling group when its systemd process is running.

  4. This step shows the creation of the new ASG, while keeping the exiting ASG in place.

  5. Upon successful creation of the new ASG, the previous deploy's ASG will be deleted.

The watchdog script to report into the ASG:

Here is the supporting Systemd Unit. It ensures the application is started first via the "Require" before it checks.

The key Terraform component to this step is the create_before_destroy. It is applied to the aws_launch_configuration and aws_autoscaling_group resources.

Along side the launch config and autoscaling group resources are some other supporting resources such as Instance Profile, IAM roles + policies, and security group settings. These resources are specific to the service and environment deployed.

Here is a view into the directory layout:

└── terraform
    ├── dev
    │   ├── environment-args.tfvars
    │   └──
    ├── prod
    │   ├── environment-args.tfvars
    │   └──
    ├── stage
    │   ├── environment-args.tfvars
    │   └──
    ├── <--- **what we looked at in this post**

Driving this CI deployment is Jenkins. The Terraform state is managed on a per service / per environment basis and stored in s3. I will go into this in more detail in a future blog post.

In a nutshell, this Terraform recipe can come it pretty handy to manage a simple CI deployment with AWS Autoscaling Groups and stateless applications!