This post will cover how to vault aws access key and secret key with vault, and using terraform how to access.

  1. Install the vault
wget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install vault

2. Start Vault Server:** Start a Vault server in dev mode for this example. Open a terminal and run the following command:

 vault server -dev

The Vault server will start running at the specified address (usually `http://127.0.0.1:8200`).

3. In another terminal, set the `VAULT_ADDR` environment variable to the Vault server address:

 export VAULT_ADDR="http://127.0.0.1:8200"

Then, initialize Vault and set an initial root token:

 vault operator init

Make note of the unseal keys and the initial root token.

4. Unseal the Vault using the unseal keys obtained from the previous step:

 vault operator unseal

5. Enable the Key-Value (KV) secrets engine to store and retrieve secrets:

 vault secrets enable -path=secrets kv-v2

6. Initialize Terraform to download the Vault provider plugin:

 terraform init

7. vault kv put secret/aws_credentials

access_key=< get from aws account> 
secret_key=<get from aws account>

8. add access key and secret key in vault

vault kv put secret/aws_credentials access_key=<access key> secret_key=<secret key>

9.  tf file for aws account

provider "vault" {
address = "http://127.0.0.1:8200"
}
data "vault_generic_secret" "aws_credentials" {
path = "secret/aws_credentials"
}
provider "aws" {
access_key = data.vault_generic_secret.aws_credentials.data["access_key"]
secret_key = data.vault_generic_secret.aws_credentials.data["secret_key"]
region = "us-west-2" # Replace with your desired AWS region
}
data "vault_generic_secret" "myapp_secret" {
path = "secret/aws_credentials"
}
resource "aws_instance" "example" {
ami = "ami-0b8987a72eee28c3d" # Replace with your desired AMI ID
instance_type = "t2.micro"
subnet_id = "subnet-0e09953db95a5ac65" # Replace with your desired subnet ID
# user_data = data.vault_generic_secret.myapp_secret.data["password"]
key_name = "my-key"
connection {
type = "ssh"
user = "ubuntu"
private_key = file("my-key.pem")
host = self.public_ip
}
}

10. Run following command

terraform plan
terraform apply