Skip to main content

3 posts tagged with "terraform"

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.

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"

Platform Engineering

· 3 min read

I came across Puppet's 2020 State of DevOps report and noticed how closely it mapped to questions I ask candidates. I've been helping with hiring lately.

We ask a deliberately broad question. The wording varies, but it usually comes down to this:

note

How would you build a highly available Kubernetes cluster on bare metal or in a public cloud, with enough capacity for heavy workloads and room to scale across development teams? Walk us through your reasoning and what you'd do in practice, starting from the very first step.

We want to deliver a platform at the push of a button. That takes IaC and a few other pieces. I'd break the work into three steps that fit together well enough to make deployment a roughly one-button operation:

  1. compute bootstrapping provisions the physical servers or VMs, networks, and other resources that will host the OS and Kubernetes. In most cases I'd use Terraform with the AWS, GCP, VMware, or OpenStack provider.

  2. provisioning configures the OS and installs a highly available Kubernetes cluster on that compute using configuration management. Managed Kubernetes in a public cloud can handle this step for you.

  3. cluster configuration adds the pieces a bare cluster needs to be useful, including public ingress, metrics and logs, and secret storage and delivery. There are two ways to install those components:

    • CiOps stores the infrastructure application definitions in Git. A pipeline runner with cluster access applies the manifests or installs the charts. Kubernetes is declarative, but the operation itself is imperative and may fail to be idempotent.
    • GitOps adds a controller that compares the running cluster with the manifests or Helm charts in Git. It reports configuration drift and can correct it automatically when self-healing is enabled.

Deployment on AWS with GitOps​

Terraform provisions the AWS infrastructure and creates an Amazon EKS cluster. EKS supplies the managed Kubernetes control plane, so there is no separate step to install it. Once the cluster is up, bootstrap Argo CD inside it. Argo CD pulls the desired state from Git and syncs platform components into Kubernetes; Git doesn't push changes to the cluster.

Takeaway: At the time, this looked like the most promising way to build Kubernetes infrastructure and worth exploring in more depth.

Links