© Brian Beach, Steven Armentrout, Rodney Bozo, Emmanuel Tsouris 2019
B. Beach et al.Pro PowerShell for Amazon Web Serviceshttps://doi.org/10.1007/978-1-4842-4850-8_2

2. Getting Started

Brian Beach1 , Steven Armentrout2, Rodney Bozo3 and Emmanuel Tsouris4
(1)
Raleigh, NC, USA
(2)
Mountlake Terrace, WA, USA
(3)
Sterling, VA, USA
(4)
North Bend, WA, USA
 

In the previous chapter, we described cloud computing and then discussed the benefits of scripting your AWS configuration. Before we get started writing these scripts, we need to create an AWS account and prepare our PowerShell environment.

We will begin by creating a new AWS account and credentials for PowerShell. Then we will install the AWS Toolkit and configure a few default values. Although this might not be the most exciting chapter, it is an important one because the examples in the rest of the book assume that you have followed the steps in this chapter.

Creating an AWS Account

If you don’t already have an Amazon Web Services (AWS) account, go to http://aws.amazon.com and click Create a Free Account to get started. If you already have one, skip ahead to the next section.

To create an AWS account, you will have to sign in using an Amazon.com account (see Figure 2-1). This can be the same account you use to shop on Amazon.com. If you are creating an AWS account for work, you might want to create a separate Amazon account using your work e-mail rather than using your personal account. If you want to create a new account, or have been living under a rock and don’t have an Amazon account already, you can create one now.

After you create an AWS account, it’s time to create an IAM account, which is discussed next.

Creating an IAM User Account

Now that you have an AWS account, you will need to create a new IAM user. (IAM stands for Identity and Access Management.) AWS has two types of users: account credentials and IAM users. The e-mail address you used to create the AWS account is called an “AWS account credential.” You should not use your account credentials for day-to-day activities on AWS. Save your AWS account credentials to change account options and access your bills. Create an IAM user for day-to-day activities instead.

IAM allows you to create multiple user accounts and configure the permissions of each user. If you already have an IAM user with administrator privileges, you can skip to the next section.

Open http://console.aws.amazon.com . If you are not already signed in, use your AWS account credential (i.e., the e-mail address used to create the account) to sign in. You will be taken to the AWS Management Console. Click Services from the menu bar at the top of the screen and search for IAM (see Figure 2-1).

From the IAM dashboard, click the Users on the left navigation and then click the Add User button. This will start the add user wizard.
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig1_HTML.jpg
Figure 2-1

AWS Console

Enter admin as the User name and choose both Programmatic access and AWS Management Console access. You can enter a password here or let the wizard generate a random password for you. Click the Next button. (See Figure 2-2.)
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig2_HTML.jpg
Figure 2-2

Add user Step 1

On the next page, click the Create group button. Enter the name admins and select the AdministratorAccess policy. Click Create group and then click Next: Tags. (See Figure 2-3.)
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig3_HTML.jpg
Figure 2-3

Add user Step 2

Skip the Tags screen by clicking the Next : Review button. Then, click the Create User button. Finally, click the Download .csv file. Keep this file somewhere safe. You will need it later.

Types of Credentials

IAM users have three types of credentials, and each one is used for a different purpose:

Username and Password – The Username and Password are used to access the Web Console. In addition to the password, you can also opt for Multi-Factor Authentication (MFA). MFA uses an authentication code for extra security. MFA requires an authentication device or smartphone application like Google Authenticator.

Access Key ID and Secret Key – The Access Key ID and Secret Key are used to access the REST API. Both PowerShell and the AWS Command-Line Interface (CLI) use the REST API. Therefore, you need to download keys to use PowerShell.

Signing Certificates – Signing Certificates are used for the SOAP web services. The SOAP service is being deprecated, so I will not discuss it in this book.

Note that not all users will have all types of credentials. An administrator that does not use the API may only have a username and password, for example, while a developer that does not have access to the Web Console may only have an Access Key ID and Secret Key.

Logging in As an IAM User

The last thing we need to do is get the custom sign-in URL for your new account. In order to sign in using your IAM username and password, you must visit the account sign-in URL. Each account has a unique sign-in URL, but the default URL is very difficult to remember; let’s change it to something we can remember.

To change the sign-in URL, return to the IAM dashboard and find the IAM user sign-in link (see Figure 2-4). Click the Customize link to specify a friendly account alias.
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig4_HTML.jpg
Figure 2-4

Setting an account alias

At this point you should sign out using the menu at the top right of the screen (see Figure 2-5).
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig5_HTML.jpg
Figure 2-5

Signing out

Finally, navigate to the custom sign-in link and sign on as admin. If you let the wizard generate a password, you can find it in the csv file you downloaded earlier.

Note that you are now logged in as an IAM user. Compare the IAM user listed in the top right corner (see Figure 2-6) to the account credential in Figure 2-3. Note the IAM user includes the “@ alias.”
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig6_HTML.jpg
Figure 2-6

Signed in as an IAM user

At this point you have an AWS account and an IAM user with administrative privileges. Next, we are going to install the AWS Tools for PowerShell and configure a few default values.

Configuring PowerShell

You can download the AWS tools from http://aws.amazon.com/powershell/ . If you are running your script on an AWS Windows instance (e.g., a server running in the AWS Cloud), the tools are already installed. If you want to run the tools on your own machine, download the installer from the preceding site.

The AWS tools are also available from the PowerShell gallery. There are two versions: AWSPowerShell and AWSPowerShell.NetCore. If you are running PowerShell on Linux, you will want to install AWSPowerShell.NetCore. For the rest of this book, I will assume you are running on Windows. However, nearly everything will work on PowerShell Core.

I usually write scripts using the PowerShell Integrated Script Environment (ISE) because it supports IntelliSense and debugging. The PowerShell ISE is a Windows feature. If it is not already enabled, you may need to enable the feature from Windows Server Explorer. This feature is enabled by default on AWS instances.

Let’s check if the AWS tools are working. Type Get-AWSRegion at the PowerShell command prompt and press Enter, as shown here.
PS> Get-AWSRegion
Get-AWSRegion will list all of the AWS regions (described in Chapter 1) around the globe, as shown in the following code output:
Region                          Name
------                          ----
us-east-1                       US East (Virginia)
...
us-east-2                       US East (Ohio)
...
us-west-1                       US West (N. California)
...
us-west-2                       US West (Oregon)
...
eu-west-1                       EU West (Ireland)
...
...

If the command succeeds, your PowerShell environment is set up correctly. Notice that we did not use the credentials we downloaded earlier. The Get-AWSRegion method does not require authentication. Before you can do anything exciting, you are going to have to supply your credentials. Let’s see how to do this in the next section.

Specifying Credentials and Region

Now that we have the AWS tools installed and PowerShell configured, let’s try something more complicated. Type the Get-EC2Instance command to list all of the instances deployed in the cloud. Remember that an instance is Amazon’s term for a server.
PS> Get-EC2Instance
Note that you have not deployed any instances yet, so this command is not expected to return anything. But when we run the command, we get the following error:
Get-EC2Instance : No credentials specified or obtained ...

Before you can use AWS, you need to log in. Remember that PowerShell uses the REST API. Therefore, you will need an access key and secret key in order to use PowerShell.

All of the AWS commands support the AccessKey and SecretKey parameters. You must include the keys you downloaded in the last section. For example, type
PS> Get-EC2Instance -AccessKey AKIA...ZHDA -SecretKey 9wVJ...iXdG
Note, however, that we still get an error:
Get-EC2Instance : No region specified or obtained ...
The credential error is gone, but now we have a new error – we also need to specify a region. Each AWS region is independent. You need to tell AWS which region you want to list the instances in. Note that you cannot list the instances in all regions in a single command. Let’s list your instances in the Northern Virginia region. Type the following:
PS> Get-EC2Instance -AccessKey AKIA...ZHDA -SecretKey 9wVJ...iXdG -Region us-east-1
This code produces the following results:
ReservationId   : r-12345678
OwnerId         : 123456789012
RequesterId     :
GroupId         : {}
GroupName       : {}
RunningInstance : {ip-10-1-1-5.brianbeach.com}

At this point, you should receive a list of your instances deployed in the specified region. If you just created a new account, you probably don’t have any instances yet. As long as you don’t get an error, it’s working correctly. This is everything you need to execute the scripts in this book, but there are still a few things we can do make life easier. For example, it would be nice to save the default credentials and region so we don’t have to add them to every command.

Setting Defaults

It can get cumbersome including the keys on every line of every script. Life would be easier if you had to specify the keys only once. Luckily, Amazon thought of this and included the Set-AWSCredentials and Set-DefaultAWSRegion commands .

Note

I am no longer including the command prompt (PS>) in my examples. From here on, most examples will be multiline scripts. I am using the PowerShell ISE to edit and run my scripts as a batch.

Just type the script into the top window and click the play button (or press the F5 key). If you prefer, you can enter these commands, one at time, at the command prompt. Personally, I prefer the IDE.
Set-DefaultAWSRegion us-east-1
Set-AWSCredentials -AccessKey ACCESS_KEY -SecretKey SECRET_KEY
Get-EC2Instance
This script results in the following:
ReservationId   : r-12345678
...

Notice that once I set a default region and credentials, I can run the Get-EC2Instance command without any parameters. This is so much easier. I can simply include these two lines at the top of the script, and I don’t have to worry about it again.

If you want to clear the defaults, you can use the Clear-AWSCredentials and Clear-DefaultAWSRegion commands . For example:
Clear-AWSCredentials
Clear-DefaultAWSRegion

Setting defaults is great, but we have to remember to set them each time we start PowerShell. We can take it one step further and persist the defaults between PowerShell sessions.

Persisting Defaults

The Initialize-AWSDefaults command will persist the credentials and region between sessions. PowerShell will remember your defaults when you restart PowerShell or reboot your computer. Once you persist the credentials, you no longer need to specify them in your script. This makes the script portable between developers and AWS accounts. Note that unlike the PowerShell profiles, persisted defaults set in the ISE also affect the command line. Type the following:
Set-DefaultAWSRegion us-east-1
Set-AWSCredentials -AccessKey ACCESS_KEY -SecretKey SECRET_KEY
Initialize-AWSDefaults
Notice the results:
Credentials retrieved from Session
Region retrieved from Session
Credentials and region will be saved in this session
When you start a new PowerShell session, the default values will be loaded automatically. For example:
Get-EC2Instance
Now, if the defaults were not already loaded, they will be loaded as needed. This command now produces the following results:
Default credentials for this shell initialized from stored default profile
Default region for this shell initialized from stored default profile
ReservationId   : r-12345678...
If you want to clear the defaults, you can use the Clear-AWSDefaults command :
Clear-AWSDefaults

We are almost done discussing defaults, but there is one more option I want to mention: stored credentials. Stored credentials allow you to store multiple credentials and switch between them quickly.

Using Stored Credentials

You may find that you have more than one set of credentials to manage. Maybe you have separate AWS accounts for development and production servers; in my opinion, this is a really good idea. (And I hope you’re not running these examples in the same account that you use to host production workloads.)

You can use the Set-AWSCredentials command we discussed earlier to create named profiles and quickly switch between them. To create a named profile, use the StoreAs attribute. For example:
Set-AWSCredentials -AccessKey ACCESS_KEY -SecretKey SECRET_KEY -StoreAs "Production"
Set-AWSCredentials -AccessKey ACCESS_KEY -SecretKey SECRET_KEY -StoreAs "Development"
Now we can use the stored credentials as an attribute to any command. For example, if you want to list the servers in the production environment, type
Get-EC2Instance -StoredCredentials Production
Here is the result:
ReservationId   : r-12345678...
And, if you want to list the servers in the development environment, type
Get-EC2Instance -StoredCredentials Development
The preceding script produces this result:
ReservationId   : r-87654321...
If you want to swap the default credentials between the development and production profiles, you can use the Set-AWSCredentials command with the StoredCredentials attribute. All subsequent commands will use the production credentials.
Set-AWSCredentials -StoredCredentials Production
You can list the various credentials you have stored using Get-AWSCredentials. For example, type
Get-AWSCredentials –ListStoredCredentials
to get this result:
Development
Production
Finally, you can remove credentials using the Clear-AWSCredentials command :
Clear-AWSCredentials -StoredCredentials Development

At this point your PowerShell environment is ready. In the next chapter, we are going to launch a few instances. Before you do that, however, you are going to need an EC2 key pair.

Using Key Pairs

Before we move on to creating instances, you will need a key pair. This key pair is used to encrypt the Windows Password for a new instance. AWS keeps the public key, and you keep the private key. When you create a Windows instance, AWS creates a local administrator account and generates a random password. It then encrypts the random password with the public key and stores the encrypted copy.

You can retrieve the password any time and decrypt it with your private key. Note that AWS does not keep the plain-text password. Therefore, only you can decrypt the password.

Caution

If you lose your private key, you will not be able to decrypt the password. Be careful with your keys!

To create a key pair, log in using your IAM admin user and choose a region. I will be using Northern Virginia, but you can select the location nearest you. Then, navigate to the EC2 service and choose Key Pairs from the left navigation. Click Create Key Pair.

Name the key pair and click Create. Your browser will download the private key. Make sure you save it. Note that the examples in this book assume your key is stored in c:awsmykey.pem.

You can also create a new key pair using the New-EC2KeyPair command . This command generates a new key pair and returns the private key. You can save the private key to a file using the Out-File command. Note that you must specify the encoding as ASCII. For example:
$KeyPair = New-EC2KeyPair -KeyName MyKey
$KeyPair.KeyMaterial | Out-File -FilePath 'c:awsMyKey.pem' -Encoding ASCII

That’s everything you need to complete the exercises in this book. If you cannot wait any longer to launch an instance, feel free to move on to Chapter 3. But, if you have the patience, I would like to tell you about one more feature: IAM roles.

Using IAM Roles

We have covered a lot of material already in this chapter, but there is one more feature I want to discuss. It is a bad idea to have your production scripts running as an individual user. What happens if that user leaves the company? If you delete her account, all of your scripts will stop working.

You could create an additional IAM user just for running production scripts. But, how do you keep those keys secret? How do you keep a disgruntled administrator you fired from using the keys to terminate all your servers? Luckily, AWS provides a solution for this, too: IAM roles.

An IAM role allows you to grant permission to an EC2 instance. This way, you don’t need keys to run PowerShell scripts. In other words, if you assign an IAM role to an instance, the instance has permission to run scripts rather than a user. Any scripts that are run on that instance are implicitly granted the permissions defined to the IAM role. Therefore, you don’t have to bother with keys at all. Although you don’t have to set credentials, you still need to set the region.

Of course this only works for instances running in AWS. You cannot use IAM roles for machines running in your data center. In addition, you have to assign the role when you create the instance; you cannot assign it later.

To create an IAM role, open the AWS Management Console and navigate to the IAM Console. (I assume you know how to do this by now. If not, go back to the “Creating a User Account” section at the beginning of this chapter.) Choose Roles from the left navigation. Then, click the Create Role button and name your new role (see Figure 2-6). I will use the name AdminRole for the scripts in this book.

There are many types of roles available. On the first screen of the create role wizard, choose AWS Service and EC2, then click Next: Permissions. (See Figure 2-7.)
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig7_HTML.jpg
Figure 2-7

Creating an IAM role

On the next screen, choose AdministratorAccess and click Next:Tags (see Figure 2-8). Note that in a real-life scenario you would want to restrict the role. With administrator permissions assigned to an EC2 instance, anyone who runs a script on that instance will have full control over your account. For the purposes of this book, this is fine, but please be more restrictive in real life.
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig8_HTML.jpg
Figure 2-8

Selecting the Amazon EC2 role

You can skip the Tags screen by clicking Next: Review. On the last screen, name the role AdminRole and click the Create role button. (See Figure 2-9.)
../images/319650_2_En_2_Chapter/319650_2_En_2_Fig9_HTML.jpg
Figure 2-9

Naming the EC2 role

We will use this role in the second exercise of Chapter 3.

Summary

In this chapter, we created an AWS account and IAM user. Then we installed the AWS Tools for PowerShell and configured our PowerShell scripting environment with a default region and credentials. Finally, we created an EC2 key pair and an IAM role. We now have everything in place to begin using the cloud. In the next chapter, we will launch a few basic instances.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset