Skip to main content

4 posts tagged with "ansible"

View All Tags

Automating macOS setup with Ansible Pull

· 2 min read

The problem​

I've been using macOS for three years and I'm on my fifth laptop replacement across two jobs. Moving to a new one is always a bit of a hassle, especially without a spare personal laptop :)

I'm not keen on restoring from Time Machine snapshots. I like treating my workstation more like a server: keep it as stateless as practical and configure it with IaC.

The setup​

I ended up with a simple setup:

  1. A local cron job runs ansible-pull -U https://github.com/kb play.yml.
  2. Ansible clones the repository and runs the playbook at the specified path. In my setup it applies to localhost.

Takeaways​

  • Keeping my workstation setup in IaC, including software, GUI apps, and config files, feels like a good investment.
  • It's convenient to apply IaC in a GitOps style, with configuration applied automatically to maintain the desired state. Here Ansible provides the automation without a full GitOps controller.

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.

Vagrant - DevOps Environment

· 3 min read

Inspiration​

I recently wrote about building a Vagrant box, and I've finally finished it 🎉. It comes in two versions:

  • A server version you access over SSH.
  • A GUI version with desktop apps preinstalled 💻.

asciicast

Here's the same process as a diagram:

Installing on Windows​

Check the resources available on your host OS:

CPU

WMIC CPU Get DeviceID,NumberOfCores,NumberOfLogicalProcessors

Look for the OS version and total RAM:

systeminfo |findstr /c:"OS Name" /c:"Total Physical Memory"

img

"Recommended resources"
  • 2 vpcu
  • 4Gi RAM

You'll need:

VirtualBox Guest Additions​

6.4. Installing the VirtualBox Guest Additions

vbguest vagrant plugin​

danger

This only worked once for me 💀.

vagrant plugin uninstall vagrant-vbguest
vagrant destroy -f
vagrant up
vagrant plugin install vagrant-vbguest
vagrant vbguest --do install

ansible galaxy​

Use my example. The Ansible role installs Guest Additions.

caution

I can't promise it will work on every machine, but it should take very little tweaking.

The secret option​

You can always search the web or YouTube for how to make VirtualBox go full screen 😉.

Good luck, and may the Force be with you!

tip

If you haven't seen this yet, now's your chance:

Toggle me!

🦖 🦕

Links

Links and articles that helped me build this:

Links

Selfmade Vagrant box

· 2 min read

I couldn't find a good box with a GUI on Vagrant Cloud.

Build process​

info

I'll use Docker as an analogy throughout.

config file​

We describe the Vagrant box (think Docker image) in an HCL configuration, much like Terraform.

source "vagrant" "ubuntu" {
add_force = true
communicator = "ssh"
provider = "virtualbox"
source_path = "ubuntu/focal64"
}

build {
name = "learn-packer"
sources = [
"source.vagrant.ubuntu"
]
}
tip

Useful commands:

packer validate packer.hcl # Validate the file
packer fmt . # Format the files and, I believe, validate them too

build​

Build the image with Packer, which plays a role similar to the Docker engine here.

packer build packer.hcl

After a while, a .box file will appear in the learn-packer directory. Think of it as the Docker image.

push​

Upload the file to Vagrant Cloud. You'll need its checksum, which you can calculate with md5, for example.

provisioner​

note

Ansible is my preferred provisioner, though shell works too.

source "vagrant" "ubuntu" {
add_force = true
communicator = "ssh"
provider = "virtualbox"
source_path = "ubuntu/focal64"
}

build {
name = "learn-packer"
sources = [
"source.vagrant.ubuntu"
]
provisioner "ansible" {
playbook_file = "./ansible/packer-playbook.yml"
}
}

post-processors​

caution

I haven't tested this.

These steps run after the build, for example publishing to Vagrant Cloud, much like docker push.

GitHub repo