To generate an AWS Access Key and Secret Access Key for use with Terraform, you need to create an IAM user or use an existing user with programmatic access. Here’s a step-by-step guide:
1. Sign in to the AWS Management Console
- Log in with your credentials at AWS Console.
2. Navigate to the IAM Management Console
- Go to the IAM Dashboard by searching for “IAM” in the AWS services search bar.
3. Create a New IAM User (Optional, if a new user is required)
Steps to create a new user:
- Click “Users” on the left sidebar and then click “Add users”.
- Enter a User name (e.g.,
terraform-user). - Select “Access Key – Programmatic Access” under “Access type”.
- Click Next to proceed to the “Permissions” section.
4. Assign Permissions to the User
- Attach a policy that grants the necessary permissions to the user:
- For full administrative access: Attach the AdministratorAccess policy.
- For limited access: Attach a custom policy or predefined policies like AmazonEC2FullAccess, AmazonS3FullAccess, etc.
5. Review and Create
- Review the user details, and click Create user.
6. Retrieve the Access Key and Secret
Once the user is created:
- You’ll see the Access Key ID and Secret Access Key on the confirmation page.
- Save these credentials securely (e.g., in a password manager or AWS Secrets Manager) because the secret key will not be shown again.
Important: If you lose the secret key, you will need to generate a new one.
7. (Optional) Generate New Keys for an Existing User
If you want to generate new keys for an existing IAM user:
- Go to IAM → Users.
- Select the user for whom you want to generate keys.
- Click the Security credentials tab.
- Scroll down to Access keys and click Create access key.
- Save the Access Key ID and Secret Access Key securely.
8. Configure AWS CLI for Terraform
To make Terraform use the generated keys, configure them in the AWS CLI:
- Run the command:
aws configure - Enter the Access Key ID and Secret Access Key when prompted.
- Specify the default region (e.g.,
us-east-1) and output format (e.g.,json).
9. Use the Keys in Terraform
Option 1: Use Environment Variables
Export the credentials as environment variables:
export AWS_ACCESS_KEY_ID="your-access-key-id"
export AWS_SECRET_ACCESS_KEY="your-secret-access-key"
Option 2: Specify in Terraform Provider Block
In your Terraform configuration file:
provider "aws" {
region = "us-east-1"
access_key = "your-access-key-id"
secret_key = "your-secret-access-key"
}
Option 3: Use Shared AWS Credentials File
Store the keys in the ~/.aws/credentials file:
[default]
aws_access_key_id = your-access-key-id
aws_secret_access_key = your-secret-access-key
Then reference the profile in Terraform:
provider "aws" {
region = "us-east-1"
profile = "default"
}
10. Secure Your Access Keys
- Avoid hardcoding the keys in Terraform files or code repositories.
- Rotate the keys periodically for better security.