Skip to main content

5 posts tagged with "aws"

View All Tags

Ansible as a Terraform provisioner

· 4 min read

Provisioning compute with IaC has two stages:

  • Bootstrapping provisions resources from a cloud provider on demand using Terraform.
  • Provisioning configures the resources you created, usually at the OS level.

From my platform engineering post.

Let's solve a simple problem: create a VM and install NGINX on it.

common​

The two examples share Terraform locals and an Ansible playbook.

locals {
// $ ssh-keygen -t ed25519 -f ~/.ssh/ansible -C ansible
ssh_keys = [
{
user = "ansible"
private_key_path = "~/.ssh/ansible"
public_key_path = "~/.ssh/ansible.pub"
},
]
// ansible alias
ssh = local.ssh_keys[0]

author = "ahorbach"
}

---

- name: Workshop aws,gcp,terraform,ansible
hosts: all
vars: {}

become: true
become_method: sudo

tasks:
- name: Ensure Nginx is at the latest version
apt:
name: nginx
state: latest
update_cache: true

- name: Make sure Nginx is running
systemd:
name: nginx
state: started

AWS​

1. provider​

Configure the provider:

provider "aws" {
region = "eu-west-1"
profile = var.aws_named_profile
}

2. data​

Use data sources to look up the default VPC, its subnet, and a recent Ubuntu AMI:

data "aws_vpc" "default" {
default = true
}

data "aws_subnet_ids" "default" {
vpc_id = data.aws_vpc.default.id
}

data "aws_ami" "ubuntu" {
most_recent = true
owners = ["099720109477"] // Canonical

filter {
name = "description"
values = ["Canonical, Ubuntu, 20.04 LTS, amd64 focal image build on*"]
}

filter {
name = "virtualization-type"
values = ["hvm"]
}
}

3. aws_security_group, aws_key_pair​

Create a security group. The server can send outbound traffic to the internet and accepts inbound connections on ports 22 (SSH) and 80 (HTTP).

resource "aws_security_group" "this" {
name = "${local.author}-sg"
description = "Allow ssh and web on port 80, and answer to everyone"
vpc_id = data.aws_vpc.default.id

ingress {
// ssh
protocol = "tcp"
from_port = 22
to_port = 22
cidr_blocks = ["0.0.0.0/0"]
}

ingress {
// web
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}

egress {
// Allow outgoing traffic from all ports
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}

Upload the public part of our SSH key to AWS:

resource "aws_key_pair" "this" {
key_name = "${local.author}-ansible"
public_key = file(local.ssh.public_key_path)
}

4. aws_instance​

resource "aws_instance" "this" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"

vpc_security_group_ids = [aws_security_group.this.id]
availability_zone = "eu-west-1b"

associate_public_ip_address = true
key_name = aws_key_pair.this.key_name

provisioner "remote-exec" { # (1)
script = <<EOF
#!/bin/bash

while [ ! -f /var/lib/cloud/instance/boot-finished ]; do
echo -e "\033[1;36mWaiting for cloud-init..."
sleep 1
done
EOF

connection {
type = "ssh"
host = self.public_ip
user = "ubuntu"
private_key = file(local.ssh.private_key_path)
}
}

provisioner "local-exec" { # (2)
command = <<EOF
ansible-playbook \
--inventory '${self.public_ip},' \
--private-key ${local.ssh.private_key_path} \
--user ubuntu \
./playbook.yml
EOF

}
tags = {
Name = "${local.author}-nginx"
}
}
  1. Wait until AWS says the VM is ready before running the Ansible playbook.
  2. Run the playbook from the machine that runs terraform apply.

GCP​

1. provider​

provider "google" {
project = var.gcp_project_id
region = "europe-central2"
zone = "europe-central2-b"
}

2. google_compute_firewall, google_os_login_ssh_public_key​

Create a service account and a firewall rule equivalent to the AWS security group:

data "google_client_openid_userinfo" "ahorbach" {}


resource "google_service_account" "this" {
account_id = "${var.gcp_project_id}-nginx"
}

resource "google_compute_firewall" "web" {
name = "web-access"
network = local.network

allow {
protocol = "tcp"
ports = ["80"]
}
source_ranges = ["0.0.0.0/0"]

target_service_accounts = [google_service_account.this.email]
}

Upload the public part of our SSH key to GCP:

resource "google_os_login_ssh_public_key" "this" {
project = var.gcp_project_id
user = data.google_client_openid_userinfo.ahorbach.email
key = file(local.ssh.public_key_path)
}

3. google_compute_instance​

Start the VM:

resource "google_compute_instance" "this" {
name = "${local.author}-nginx"
machine_type = "e2-micro"
zone = "europe-central2-b"

boot_disk {
initialize_params {
image = "ubuntu-2004-focal-v20230213"
}
}

network_interface {
network = local.network
access_config {}
}

service_account {
email = google_service_account.this.email
scopes = ["cloud-platform"]
}

// creater users and put public keys
metadata = {
ssh-keys = join("\n", [for key in local.ssh_keys : "${key.user}:${file(key.public_key_path)}"])
}

provisioner "remote-exec" {
inline = ["echo 'Waint until SSH is ready'"]

connection {
type = "ssh"
user = local.ssh.user
private_key = file(local.ssh.private_key_path)
host = self.network_interface.0.access_config.0.nat_ip
}
}

provisioner "local-exec" {
command = <<EOF
ansible-playbook \
--inventory '${self.network_interface.0.access_config.0.nat_ip},' \
--private-key ${local.ssh.private_key_path} \
--user ${local.ssh.user} \
./playbook.yml
EOF
}
}
  • You can configure VM operating systems across clouds using the same Ansible playbooks.
  • Other options include building an image with Packer and Ansible for reuse, or using pull-based configuration management such as ansible-pull.
  • The Ansible provisioner is equivalent to running ansible-playbook --inventory '34.118.12.194,' --private-key ansible --user ansbile playbook.yml locally after terraform apply.
  • Source code.

IRSA: accessing the AWS API from an EKS pod

· 6 min read

Suppose an application running in an EKS pod needs access to a private S3 bucket in the same AWS account.

Here are some ways to do it.

IAM user​

This option lets you debug the application locally.

The application calls the AWS API through an SDK. Pass the client the aws_access_key_id and aws_secret_access_key for an IAM user with access to the resource.

Configure the AWS IAM resources as follows:

AWS configuration​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}

k8s configuration​

---

apiVersion: apps/v1
kind: Deployment
...
spec:
...
template:
...
spec:
containers:
- name: s3-app
...
env:
- name: AWS_ACCESS_KEY_ID
valueFrom:
secretKeyRef:
name: s3-app
key: aws_access_key_id
- name: AWS_SECRET_ACCESS_KEY
valueFrom:
secretKeyRef:
name: s3-app
key: aws_secret_access_key

IRSA​

IRSA stands for IAM Roles for Service Accounts. It establishes trust between an AWS IAM role and a Kubernetes ServiceAccount through the EKS cluster's OIDC provider.

Attach the same IAM policy to the role that you attached to the user in the previous example. Containers in a pod using that ServiceAccount can then obtain the credentials they need.

AWS configuration​

Configure IAM as follows:

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}

k8s configuration​

---

apiVersion: v1
kind: ServiceAccount
metadata:
name: s3-app
namespace: dev
annotations:
eks.amazonaws.com/role-arn: 'arn:aws:iam::<aws_account_id>:role/s3-app' # (1)
  1. ARN of the IAM role created by the iam-assumable-role-with-oidc module

Verification​

Open a shell in the pod and look for these environment variables:

env | grep AWS
AWS_DEFAULT_REGION=<aws_region>
AWS_REGION=<aws_region>
AWS_ROLE_ARN=arn:aws:iam::<aws_account_id>:role/s3-app
AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token

Decode the token at /var/run/secrets/eks.amazonaws.com/serviceaccount/token on https://jwt.io/ to see these claims:

{
"aud": [
"sts.amazonaws.com"
],
"exp": 1673637993,
"iat": 1673551593,
"iss": "https://oidc.eks.<aws_region>.amazonaws.com/id/<HEX_HASH>",
"kubernetes.io": {
"namespace": "test",
"pod": {
"name": "s3-app-<replicaSet>-<random-hash>",
"uid": "47a2e254-d0d3-44bc-acdc-ef8f07a9f63e"
},
"serviceaccount": {
"name": "s3-app",
"uid": "91bb19bc-dab8-4c72-9718-eac7adbc4b59"
}
},
"nbf": 1673551593,
"sub": "system:serviceaccount:dev:s3-app"
}

Check access to the bucket:

aws s3 ls --recursive s3://bucket-s3-app
2021-12-14 15:07:52 47134393 app/my-cool.stuff
...

The Amazon EKS pod identity webhook sets this up.

Cross account irsa​

Now suppose the application runs in an EKS pod in AWS account A and needs access to a private S3 bucket in AWS account B.

The diagram shows the CI account as A and the target account as B:

img

warning

In most cases, I'd try to avoid designing a system where a pod in account A has to call the AWS API for a resource in account B.

AWS account A​

AWS configuration​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
// This policy allows assuming the role in account B
{
"Version":"2012-10-17",
"Statement":[
{
"Action":"sts:AssumeRole",
"Resource":"arn:aws:iam::<aws_account_id_B>:role/s3-app-B",
"Effect":"Allow",
"Sid":""
}
]
}
EOF
}

k8s configuration​

---

apiVersion: v1
kind: ServiceAccount
metadata:
name: s3-app
namespace: dev
annotations:
eks.amazonaws.com/role-arn: 'arn:aws:iam::<aws_account_id_A>:role/s3-app-A' # (1)
  1. ARN of the IAM role that trusts this ServiceAccount and can assume the role in account B

AWS account B​

resource "aws_iam_policy" "this" {
name = "s3-app"
policy = <<EOF
{
"Version":"2012-10-17",
"Statement":[
{
"Sid":"",
"Effect":"Allow",
"Action": "s3:*",
"Resource":[
"arn:aws:s3:::${aws_s3_bucket.this.bucket}",
"arn:aws:s3:::${aws_s3_bucket.this.bucket}/*"
]
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "this" {
role = aws_iam_role.this.name
policy_arn = aws_iam_policy.this.arn
}

Verification​

Open a shell in the pod and look for the same environment variables:

# env
env | grep AWS
AWS_DEFAULT_REGION=<aws_region>
AWS_REGION=<aws_region>
AWS_ROLE_ARN=arn:aws:iam::<aws_account_id_A>:role/s3-app-A
AWS_WEB_IDENTITY_TOKEN_FILE=/var/run/secrets/eks.amazonaws.com/serviceaccount/token

The JWT has the same claims as before.

Trying to access the S3 bucket returns an error:

aws s3 ls --recursive s3://bucket-s3-app
An error occurred (AccessDenied) when calling the ListObjectsV2 operation: Access Denied

Add this configuration:

cat <<EOF >>~/.aws/config
[profile A]
role_arn = arn:aws:iam::<aws_account_id_A>:role/s3-app-A
web_identity_token_file = /var/run/secrets/eks.amazonaws.com/serviceaccount/token
[profile B]
role_arn = arn:aws:iam::<aws_account_id_B>:role/s3-app-B
source_profile = A
role_session_name = xactarget
EOF

Try again with the named profile:

aws s3 ls --recursive s3://bucket-s3-app --profile B
2021-12-14 15:07:52 47134393 app/my-cool.stuff
...

Done 🔥

Terraformer - reverse Terraform

· One min read

What it does​

https://github.com/GoogleCloudPlatform/terraformer

Terraformer turns existing cloud resources into Terraform code. It's useful when you're learning AWS and Terraform and want to export resources you created in the console for a course. It's also handy when bringing existing infrastructure under IaC.

Usage​

info

Here's what worked for me. I wouldn't call it best practice.

Export the AWS API credentials.

export AWS_DEFAULT_PROFILE=my-profile # ~/.aws/credentials
export AWS_ACCESS_KEY_ID=id
export AWS_SECRET_ACCESS_KEY=key

You'll also need the Terraform aws provider:

terraform {
required_version = ">= 1.3.0"

required_providers {
aws = {
source = "hashicorp/aws"
version = "4.42.0"
}
}
}

Initialize the provider, then run Terraformer against the AWS resource you want to import.

terraform init # Initialize the provider in ./.terraform
terraformer import aws --resources=route53 --regions=us-east-1 --profile my-profile
terraformer import aws --resources=route53 --regions=us-east-1 --profile my-profile --filter="Type=route53_zone;Name=tags.Name;Value=my.example.com"

Kubed - secret sync between k8s clusters in different aws accounts

· 9 min read

Background and architecture​

1) aws account mc-legacy​

img

There's a legacy application running in an AWS account:

  1. Route 53 has a registered domain, <my-company>.io, and a matching hosted zone.
  2. The record for <my-service>.<my-company>.io points to <lb>.<my-company>.io.
  3. The load balancer sends traffic to an Auto Scaling group (ASG).
  4. The ASG manages the EC2 instances that run <my-service>.

2) aws account mc-project​

img

We decide to move the application to Kubernetes, giving each team its own AWS account and cluster:

  1. Create a Network Load Balancer in AWS named <lb-my-project>.
  2. Its target groups point to EC2 instances running the ingress controller pods.
  3. Once a request reaches the ingress controller, the Ingress routes it through a Kubernetes Service to the pods behind <my-service>.

3) combine​

img

The Route 53 record for <my-service>.<my-company>.io now points to the CNAME for <lb-my-project>. Traffic gets through, but TLS isn't terminated.

The <my-company>.io zone is too important to hand over to controllers like external-dns or cert-manager.

At the same time, there can be many project accounts and Kubernetes clusters, and I don't want to copy the TLS Secret by hand.

4) Concept​

img

  1. Create a dedicated management AWS account and Kubernetes cluster.
  2. Install the Secret containing the wildcard TLS certificate for *.<my-company>.io in that cluster.
  3. The Kubed controller syncs the Secret to the other Kubernetes clusters using annotations.
  4. The Ingress references that Secret and terminates TLS traffic.

Configuration​

info

In the examples below, the role for mc-mgmt is called kubed-master and the role for each mc-project-* is called kubed-follower.

AWS IAM RBAC​

info

In the diagram, mc-mgmt is CI and mc-project is Target.

img

Set up cross-account IAM roles and Kubernetes RBAC so Kubed in mc-mgmt can manage Secrets in clusters in other AWS accounts, such as mc-project.

mc-mgmt aka kubed-master​

locals {
kubed_followers_arns = [
for _, id in local.aws_accounts_map : "arn:aws:iam::${id}:role/kubed-follower"
]
}

module "iam_assumable_role_kubed_master" {
source = "terraform-aws-modules/iam/aws//modules/iam-assumable-role-with-oidc"
version = "4.2.0"

create_role = true
role_name = "kubed-master"

provider_url = replace(local.cluster_oidc_issuer_url, "https://", "")

role_policy_arns = [
aws_iam_policy.kubed_master.arn,
aws_iam_policy.kubed_eks.arn,
]

oidc_fully_qualified_subjects = [
"system:serviceaccount:kube-system:kubed"
]
}

data "aws_iam_policy_document" "kubed_master" {
statement {
sid = "kubedMaster"
effect = "Allow"
actions = [
"sts:AssumeRole",
]
resources = local.kubed_followers_arns
}
}

resource "aws_iam_policy" "kubed_master" {
name = "kubed-master"
policy = data.aws_iam_policy_document.kubed_master.json
}

data "aws_iam_policy_document" "kubed_eks" {
statement {
sid = "kubedEks"
effect = "Allow"
actions = [
"eks:DescribeCluster",
"eks:ListClusters"
]
resources = ["*"]
}
}

resource "aws_iam_policy" "kubed_eks" {
name = "kubed-eks"
policy = data.aws_iam_policy_document.kubed_eks.json
}

mc-project aka kubed-follower​

locals {
mc_mgmt_id = "<mc-mgmt_id>"
}

data "aws_iam_policy_document" "kubed_follower_assume" {
statement {
sid = "kubedFollowerAssume"
effect = "Allow"
principals {
identifiers = toset(["arn:aws:iam::${local.mc_mgmt_id}:role/kubed-master"])
type = "AWS"
}
actions = [
"sts:AssumeRole",
]
}
}

data "aws_iam_policy_document" "kubed_follower" {
statement {
sid = "kubedEks"
effect = "Allow"
actions = [
"eks:DescribeCluster",
"eks:ListClusters"
]
resources = ["*"]
}
}


resource "aws_iam_policy" "kubed_follower" {
name = "kubed-follower"
policy = data.aws_iam_policy_document.kubed_follower.json
}


resource "aws_iam_role" "kubed_follower" {
name = "kubed-follower"
description = "IAM role which allows kubed sync secrets from mc-mgmt to this account"
assume_role_policy = data.aws_iam_policy_document.kubed_follower_assume.json
managed_policy_arns = [aws_iam_policy.kubed_follower.arn]
}

ServiceAccount kubed​

Add this annotation to the kubed-master ServiceAccount:

annotations:
eks.amazonaws.com/role-arn: arn:aws:iam::<mc-mgmt_id>:role/kubed-master

ConfgiMap aws-auth​

apiVersion: v1
kind: ConfigMap
metadata:
name: aws-auth
namespace: kube-system
data:
mapRoles: |
- "groups":
- "system:masters"
"rolearn": "arn:aws:iam::<mc-mgmt_id>:role/kubed-master"
"username": ""
...

Docker image​

The upstream image is based on scratch and contains just the Kubed binary. We also need AWS CLI tools to generate the kubeconfig.

FROM appscode/kubed:v0.13.2 as downloader

FROM alpine:3.17

COPY --from=downloader /kubed /usr/bin/kubed

RUN apk add --no-cache \
curl~=7.86 \
py3-pip~=22.3 \
&& pip install --no-cache-dir \
awscli~=1.27 \
&& curl -Lo aws-iam-authenticator https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v0.5.9/aws-iam-authenticator_0.5.9_linux_amd64 \
&& chmod +x aws-iam-authenticator \
&& mv aws-iam-authenticator /usr/bin/

RUN addgroup --gid 1950 app \
&& addgroup --gid 1000 app \
&& adduser \
--uid 1000 \
--home /home/app \
--shell /bin/ash \
--ingroup app \
--disabled-password \
app \
&& addgroup app app

USER 1000
WORKDIR /home/app

ENTRYPOINT ["/usr/bin/kubed"]

K8s controller​

The mc-mgmt cluster also runs a regular Kubed instance installed with the Helm chart. We reuse its Kubernetes RBAC configuration.

danger

This method can be destructive. A misconfigured kubed-master can reverse the direction of Secret synchronization between namespaces. I recommend running kubed-master in a dedicated cluster.

---
apiVersion: v1
kind: ConfigMap
metadata:
name: kubed-master-aws
namespace: kube-system
data:
credentials: |-
[mc-mgmt]
role_arn = arn:aws:iam::<mc-mgmt_id>:role/kubed-master
web_identity_token_file = /var/run/secrets/eks.amazonaws.com/serviceaccount/token
[mc-project]
role_arn = arn:aws:iam::<mc-project_id>:role/kubed-follower
source_profile = mc-mgmt
role_session_name = mc-project
generate-kubeconfig.sh: |-
#!/bin/bash
set -eux

aws eks update-kubeconfig --name mc-project-k8s --alias mc-project-k8s --profile mc-project

# NOTE: mc-mgmt-k8s should the last due to current-context
aws eks update-kubeconfig --name mc-mgmt-k8s --alias mc-mgmt-k8s --profile mc-mgmt

Synchronizing configuration​

---

apiVersion: v1
kind: ConfigMap
metadata:
name: cross-acc-sync-demo
namespace: prod
annotations:
kubed.appscode.com/sync-contexts: "mc-project-k8s"
data:
foo: bar
spam: eggs

Synchronization behavior​

info

Here, configuration means a ConfigMap or Secret.

  • Sync runs from the namespace named in the controller flags to a namespace with the same name in each follower cluster. Annotations and labels from the source aren't copied to the followers.
  • Restarting the controller pod or updating the source object's .data triggers sync. Deleting the object from a follower cluster doesn't automatically recreate it.
  • Deleting the source object in the master account deletes it from all followers.
  • If a follower runs its own Kubed instance to sync across namespaces, you can annotate the object manually and let that controller distribute it. Updating .data in the master syncs the Secret without overwriting that annotation.

Add the annotation in the follower cluster:

kubectl --context mc-project annotate cm cross-acc-sync-demo "kubed.appscode.com/sync=sync/kubed-master=true"

Label another namespace in the follower cluster so the local Kubed instance syncs the ConfigMap into it.

---

kind: Namespace
apiVersion: v1
metadata:
name: env-ahorbach
labels:
name: env-ahorbach
sync/kubed-master: "true"

AWS Free Tier and a Packer Tutorial

· 2 min read

Background​

When I was learning AWS from a YouTube playlist, I built a VPC across two Availability Zones with several subnets. The private subnets used NAT gateways. The course never mentioned that NAT gateways were outside the Free Tier. The two gateways cost me about $6 in a couple of days. That stung, so I set up a billing alarm.

#!NOTE

Here's the ADV-IT course.

What happened​

I had recently been learning to build artifacts with Packer. After experimenting on AWS, I deleted all the AMIs in the relevant region through the console and moved on.

A week later I saw another email from AWS. My personal Gmail sometimes gets billing reports from them, usually empty, and invitations to re:Invent.

alert

I'd used 85% of my Free Tier allowance for EBS snapshots.

info

The AWS Free Tier page lists the monthly allowances for each resource.

It turns out Packer had created these snapshots alongside the AMIs.

snapshots

Lessons learned
  • Start by setting up a non-root identity. Then set up billing alerts. I'd pick a 50% threshold because I burned through my allowance fast.
  • If you're writing a tutorial, call out which resources fall outside the Free Tier and which have tight limits.