AWS IAM Security Through the Command Line and SDKs (Java, Ruby, and PHP)‏

Amazon security requires the use of AWS IAM with temporary authentication credentials. We’ll explore implementation via the command line and SDKs.

Cloud security is shared between AWS and its customers. Amazon Web Services Security takes responsibility for the compute and networking layers (security of the cloud), while we’re on the hook for our instances, networks, web applications, and databases (security in the cloud). But, as I discussed in a previous post on AWS security, Amazon also provides you with powerful tools to help you maintain your side of the deal; especially their Identity and Access Management system (IAM).

IAM allows you to create and manage permissions for multiple users. It works on the philosophy of least privilege, by providing only the precise rights a user or role will need to do exactly their task and nothing more. AWS best practices are, as the name suggests, the very best way to tighten your AWS  IAM security. While most best practices can be implemented without modification, using IAM roles for apps or scripts running on EC2 instances might require a little work. In this post, we’ll see some examples of code-based IAM role implementation in your applications.

What is an AWS IAM role and how does it work

When AWS IAM users want to access the AWS Management Console, they log in using their usernames and passwords. Programmatic access to AWS services requires an Access Key and Secret Key. Your keys might look something like this (use this guide to create your own keys):

aws_access_key_id = ARTDOSFODNN7EXAMPLE
aws_secret_access_key = wJalrXUtnTRSMI/K756ENG/bPxRfiCYEXAMPLEKEY

You could hard code your access keys in your application to enable access to AWS services like S3 or DynamoDB, but anyone with access to the code will be able to see the keys in plain text. If your server gets hacked, imagine the consequences of having left code like this lying around:

AWS IAM codeInstead of the above code, you can completely avoid this vulnerability by using an IAM role, which lets you securely distribute keys to your users and applications. IAM role credentials can (and should) be rotated regularly and temporary credentials provided for service access. If your application needs to access objects in an s3 bucket, temporary security credentials are provided to the host ec2 instance. IAM roles for EC2 instances also work within Amazon Virtual Private Clouds:

Amazon Virtual Private Clouds

Benefits:

  • No need to share permanent security credentials.
  • Uses temporary security credentials when making requests from running EC2 instance. Effective Amazon security requires the use of AWS IAM with temporary authentication credentials: we’ll explore implementation via the command line and SDKs to AWS services.
  • Integrated with All AWS Software Development Kits (SDKs) and the command line interface tool (CLI).

Creating an AWS IAM role

  1. Log into the IAM console.
  2. Click on Roles on the left panel, and then click Create New Role.
  3. Specify a descriptive Role name.AWS IAM role
  4. Select Role Type as EC2.
    AWS IAM Role Type
  5. On the Attach Policy page, you can either select an existing policy or go back and create a new policy as per your needs.
  6. Review the role information, and then click Create Role.
  7. You can launch an instance using either a CLI or the Console: in Ec2 dashboard, click Launch Instance.
  8. Select your AMI, then select an instance type and click Next: Configure Instance Details.
  9. On the Configure Instance Details page, Specify the role when you launch your instances.AWS IAM instance configure instance details
  10. Once this is done, your application will retrieve a set of temporary credentials and use them in your application.

Using AWS IAM Roles with the command line interface

Here’s a simple script to launch an instance using the AWS CLI. As you can see for yourself, we have included no AWS Keys. The “/etc/profile.d/aws-apitools-common.sh” file provides all the authentication you’ll need at run time (note, that if you’re running an AMI besides Amazon Linux, you may need to install this file manually).

#!/bin/bash
. /etc/profile.d/aws-apitools-common.sh
aws ec2 run-instances --image-id ami-1ecae776 --region us-east-1 --placement AvailabilityZone=us-east-1b --instance-type t2.large --key-name demo-key --subnet-id subnet-45874145 --security-group-ids sg-1254854

Using AWS IAM Roles with the PHP SDK

When using an IAM role with a PHP application, you can create caching layers on top of your IAM role credentials to specify a credentials cache using the credentials.cache option in a client’s factory method, or in a service builder configuration file. The configuration setting (credentials.cache) should be configured to an object that implements Guzzle’s CacheAdapterInterface . A credential’s cache can also be used in a service builder configuration.

<?php
// File saved as /path/to/custom/config.php
use Doctrine\Common\Cache\FilesystemCache;
use Guzzle\Cache\DoctrineCacheAdapter;
$cacheAdapter = new DoctrineCacheAdapter(new FilesystemCache('/tmp/cache'));
return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'credentials.cache' => $cacheAdapter
            )
        )
    )
);

Using AWS IAM Roles with the Java SDK

In order to use the AWS java SDK to connect AWS IAM service, all dependent Packages related to AWS IAM and AWS credentials need to be specified in the build path. The Java SDK uses “Class InstanceProfileCredentialsProvider” that loads credentials from the Amazon EC2 Instance Metadata Service, which retrieves temporary AWS credentials that have the same permissions as the IAM role associated with our EC2 instance. At the start of your program, you need to import the “com.amazonaws.auth.*” class.

import com.amazonaws.auth.profile.ProfileCredentialsProvider;

Using AWS IAM Roles with the Ruby SDK

In the Ruby SDK, EC2Provider objects retrieve credentials with the same permissions as the IAM role. These credentials refresh regularly to get access to AWS services.

AWS.config(:credential_provider => AWS::Core::CredentialProviders::EC2Provider.new)

Here’s a sample program that will download an object from AWS S3. As you can see, we have used no credentials within the code.

require 'rubygems'
require 'aws-sdk'
s3 = AWS::S3.newaws-iam-instance
bucket_name = 'text-content'
obj_name = 'text-object.txt'
document = s3.buckets[bucket_name].objects[obj_name]
File.open(obj_name, "w") do |f|
  f.write(document.read)
end
puts "'#{obj_name}' copied from S3."

Avatar

Written by

Nitheesh Poojary

My professional IT career began nine years back when I was just out of my college. I worked with a great team as an infrastructure management engineer, managing hundreds of enterprise application servers. I found my passion when I got the opportunity to work with Cloud technologies: I'm addicted to AWS Cloud Services, DevOps engineering, and all the cloud tools and technologies that make engineers' lives easier. Currently, I am working as a Solution Architect in SixNines IT. We are an experienced team of engineers that have helped hundreds of customers move to the cloud responsibly. I have achieved 5 AWS certifications, happily helping fellow engineers across the globe through my blogs and answering questions in various forums.

Related Posts

Avatar
Michael Sheehy
— August 19, 2019

What Exactly Is a Cloud Architect and How Do You Become One?

One of the buzzwords surrounding the cloud that I'm sure you've heard is "Cloud Architect." In this article, I will outline my understanding of what a cloud architect does and I'll analyze the skills and certifications necessary to become one. I will also list some of the types of jobs ...

Read more
  • AWS
  • Cloud Computing
Avatar
Nitheesh Poojary
— August 16, 2019

Boto: Using Python to Automate AWS Services

Boto allows you to write scripts to automate things like starting AWS EC2 instances Boto is a Python package that provides programmatic connectivity to Amazon Web Services (AWS). AWS offers a range of services for dynamically scaling servers including the core compute service, Elastic...

Read more
  • Automated AWS Services
  • AWS
  • Boto
  • Python
Avatar
Andrew Larkin
— August 13, 2019

Content Roadmap: AZ-500, ITIL 4, MS-100, Google Cloud Associate Engineer, and More

Last month, Cloud Academy joined forces with QA, the UK’s largest B2B skills provider, and it put us in an excellent position to solve a massive skills gap problem. As a result of this collaboration, you will see our training library grow with additions from QA’s massive catalog of 500+...

Read more
  • AWS
  • Azure
  • content roadmap
  • Google Cloud Platform
Avatar
Adam Hawkins
— August 9, 2019

DevSecOps: How to Secure DevOps Environments

Security has been a friction point when discussing DevOps. This stems from the assumption that DevOps teams move too fast to handle security concerns. This makes sense if Information Security (InfoSec) is separate from the DevOps value stream, or if development velocity exceeds the band...

Read more
  • AWS
  • cloud security
  • DevOps
  • DevSecOps
  • Security
Avatar
Stefano Giacone
— August 8, 2019

Test Your Cloud Knowledge on AWS, Azure, or Google Cloud Platform

Cloud skills are in demand | In today's digital era, employers are constantly seeking skilled professionals with working knowledge of AWS, Azure, and Google Cloud Platform. According to the 2019 Trends in Cloud Transformation report by 451 Research: Business and IT transformations re...

Read more
  • AWS
  • Cloud skills
  • Google Cloud
  • Microsoft Azure
Avatar
Andrew Larkin
— August 7, 2019

Disadvantages of Cloud Computing

If you want to deliver digital services of any kind, you’ll need to estimate all types of resources, not the least of which are CPU, memory, storage, and network connectivity. Which resources you choose for your delivery —  cloud-based or local — is up to you. But you’ll definitely want...

Read more
  • AWS
  • Azure
  • Cloud Computing
  • Google Cloud Platform
Joe Nemer
Joe Nemer
— August 6, 2019

Google Cloud vs AWS: A Comparison (or can they be compared?)

The "Google Cloud vs AWS" argument used to be a common discussion among our members, but is this still really a thing? You may already know that there are three major players in the public cloud platforms arena: Amazon Web Services (AWS), Microsoft Azure, and Google Cloud Platform (GCP)...

Read more
  • AWS
  • Google Cloud Platform
  • Kubernetes
Avatar
Stuart Scott
— July 29, 2019

Deployment Orchestration with AWS Elastic Beanstalk

If you're responsible for the development and deployment of web applications within your AWS environment for your organization, then it's likely you've heard of AWS Elastic Beanstalk. If you are new to this service, or simply need to know a bit more about the service and the benefits th...

Read more
  • AWS
  • elastic beanstalk
Avatar
Stuart Scott
— July 26, 2019

How to Use & Install the AWS CLI

What is the AWS CLI? | The AWS Command Line Interface (CLI) is for managing your AWS services from a terminal session on your own client, allowing you to control and configure multiple AWS services and implement a level of automation. If you’ve been using AWS for some time and feel...

Read more
  • AWS
  • AWS CLI
  • Command line interface
Alisha Reyes
Alisha Reyes
— July 22, 2019

Cloud Academy’s Blog Digest: July 2019

July has been a very exciting month for us at Cloud Academy. On July 10, we officially joined forces with QA, the UK’s largest B2B skills provider (read the announcement). Over the coming weeks, you will see additions from QA’s massive catalog of 500+ certification courses and 1500+ ins...

Read more
  • AWS
  • Azure
  • Cloud Academy
  • Cybersecurity
  • DevOps
  • Kubernetes
Avatar
Stuart Scott
— July 18, 2019

AWS Fundamentals: Understanding Compute, Storage, Database, Networking & Security

If you are just starting out on your journey toward mastering AWS cloud computing, then your first stop should be to understand the AWS fundamentals. This will enable you to get a solid foundation to then expand your knowledge across the entire AWS service catalog.   It can be both d...

Read more
  • AWS
  • Compute
  • Database
  • fundamentals
  • networking
  • Security
  • Storage
Avatar
Adam Hawkins
— July 17, 2019

How to Become a DevOps Engineer

The DevOps Handbook introduces DevOps as a framework for improving the process for converting a business hypothesis into a technology-enabled service that delivers value to the customer. This process is called the value stream. Accelerate finds that applying DevOps principles of flow, f...

Read more
  • AWS
  • AWS Certifications
  • DevOps
  • DevOps Foundation Certification
  • Engineer
  • Kubernetes