返回资讯中心
外部精选
软件工程
#开发者实时流

OpenTofu 与 Ansible 分工协作:前者建基础设施,后者做配置管理

来源标题:OpenTofu builds the house, Ansible furnishes it

OpenTofu 负责搭建基础设施,Ansible 负责后续配置与 furnishings。文章将二者定位为互补工具:OpenTofu 管理资源生命周期,Ansible 处理配置细节,配合使用可覆盖从创建到配置的完整流程。

Hacker News 最新speckx2026/11/22 · 今天30 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

If OpenTofu is the thing that builds your infrastructure, Ansible is the thing that configures it. While there is some overlap between the two, you should have each set of code do its own thing.

I think about OpenTofu as the construction team that builds the house, while Ansible is the team that puts the stuff inside (appliances, furniture, decorations, etc.). That is, OpenTofu will build the server, and Ansible will configure it.

As I worked through learning Ansible, I watched some videos and did some tutorials. But what really worked for me to learn it was to identify what I want to have installed and configured on any new server.

To that end, the things I want the most out of a new server are:

The playbook below covers all six (plus setting the hostname and timezone), with one assist from OpenTofu: closing off public SSH for item 6 is done with a cloud firewall rather than in Ansible. The one exception is Docker: Coolify installs it when it sets up a server, so I leave that to Coolify.

In order to do this, I used 12 different modules.

Below, I'll walk through my initial playbook step by step, with a final version of it. 1

The Ansible playbook I created had the following format:

  • name: hosts: vars: tasks:
  • name: module: parameters: handlers:
  • name: module: parameters:

I created a .env file to hold various secrets. In order to access them, I set up a vars key like this:

  • name: Bootstrap server hosts: lab vars: username: "{{ lookup('env', 'BOOTSTRAP_USERNAME') }}" user_password: "{{ lookup('env', 'BOOTSTRAP_PASSWORD') }}" ts_authkey: "{{ lookup('env', 'TS_AUTHKEY') }}" release: "{{ ansible_facts['distribution_release'] }}"

Each of the blocks below would go under the tasks key from above.

This module asserts that a given expression is true. In order to require environment variables, we have to assert that their length is greater than 0. To do this I have this block:

  • name: Require environment variables ansible.builtin.assert: that:
  • username | length > 0
  • user_password | length > 0
  • ts_authkey | length > 0 fail_msg: BOOTSTRAP_USERNAME, BOOTSTRAP_PASSWORD, and TS_AUTHKEY must be set (run via op run --env-file=.env)

Because we set up the variables in the setup step above, this is just ensuring that the data read from the environment variables is present.

This module manages apt packages. Since my server is running Ubuntu, I can use apt for package management. If you're using a different distro, you'll want to change this to use its package manager.

  • name: Update apt cache and upgrade packages ansible.builtin.apt: update_cache: true upgrade: dist

There are two parameters defined here:

I also use apt to install the tools I want on every server:

  • name: Install tools ansible.builtin.apt: name: [fish, git, direnv] state: present

ansible.builtin.hostname¶

This module manages the hostname for the server.

  • name: Set hostname ansible.builtin.hostname: name: "{{ inventory_hostname }}"

You'll notice here that the name is set to "{{ inventory_hostname }}". The hostname that is being used is stored in my inventory file (more on that later). This prevents hardcoding the hostname and having a potential hostname collision on servers.

  • name: Create a user ansible.builtin.user: name: "{{ username }}" groups: sudo append: true shell: /usr/bin/fish create_home: true password: "{{ user_password | password_hash('sha512', 65534 | random(seed=inventory_hostname) | string) }}" no_log: true

The command above will create the user specified in the environment variables, add them to the sudo group, set their shell to fish (installed in an earlier task) and create a home directory for them. It will also set the password for the user and hash it with sha512. The append parameter adds the user to the sudo group without removing them from any other groups.

If it were set to false, then on each run the user would be removed from any other groups they'd been added to (either manually on the server OR via a task in a different playbook, or a task before).

The no_log: true keeps Ansible from printing the task's arguments (including the password hash) in its output.

The copy module will copy files to remote locations, similar to scp or rsync. Under the hood it uses SFTP or SCP to move the file, controlled by the transfer_method setting in the [ssh_connection] section of ansible.cfg. The default, smart, tries SFTP first and falls back to SCP, so I didn't need to set it.

  • name: Copy ssh configuration ansible.builtin.copy: src: 10-hardening.conf dest: /etc/ssh/sshd_config.d/ owner: root group: root mode: "0644" validate: /usr/sbin/sshd -t -f %s notify: Reload ssh

There are several parameters here. The src defaults to looking at the files directory. The dest indicates where the file will be copied to. The validate parameter ensures that the file copied over is valid, which prevents a broken config from locking you out.

The notify task keyword triggers a handler which is defined later.

This module will add and remove deb822 formatted repositories.

Here I'm adding the Tailscale apt repository to the server. The {{ release }} was defined in the vars setup above and allows me to get the correct version of Tailscale for the version of Ubuntu that I'm running.

With the repository in place, Tailscale can be installed using the apt module from earlier:

  • name: Install tailscale ansible.builtin.apt: name: tailscale state: present update_cache: true

Setting update_cache: true is important here so apt picks up the newly added repository before trying to install from it.

This module allows you to run a command on a target machine. I used it a few times in my setup.

  • name: Check tailscale status ansible.builtin.command: tailscale status --json register: ts_status changed_when: false failed_when: false check_mode: false
  • name: Join tailnet ansible.builtin.command: tailscale up --authkey={{ ts_authkey }} when: (ts_status.stdout | from_json).BackendState != 'Running' no_log: true changed_when: true

Above there is a command to check the status of Tailscale on the server. The output is saved into a variable called ts_status which is then used to check the state of Tailscale. If it's not running, the server joins the tailnet using the {{ ts_authkey }} that was defined above in the vars section.

One caveat: if the tailscaled service isn't running yet, tailscale status --json returns nothing and the from_json filter will fail. In practice the apt install starts the service, so this hasn't bitten me.

The service module manages services on remote hosts.

handlers:

  • name: Reload ssh ansible.builtin.service: name: ssh state: reloaded

Here I'm creating a handler (which was referenced above in the Copy ssh configuration task in the ansible.builtin.copy section).

This handler will reload ssh if a new configuration was copied to the remote host. The name here has to match the notify parameter exactly in order for it to be called.

This module adds or removes an SSH authorized key to allow passwordless entry into a server.

  • name: Add SSH to user ansible.posix.authorized_key: user: "{{ username }}" state: present key: "{{ lookup('file', '~/.ssh/id_ed25519.pub') }}"

Here I'm setting the user and copying the id_ed25519.pub to the server so that {{ username }} can just SSH into the server without the use of a password.

This allows you to configure the timezone setting for the remote host.

  • name: Set timezone to America/Los_Angeles become: true community.general.timezone: name: America/Los_Angeles

Since I live in the America/Los_Angeles timezone, I'm setting the server timezone to match me.

The become: true isn't actually needed here, since the inventory connects as root and every task already runs with root privileges. It would matter if you connected as a non-root user, in which case you'd want become: true at the play level rather than on a single task.

This module unpacks an archive, optionally downloading it first. Fish, git, and direnv are installed with apt, but Starship and Atuin aren't packaged for Ubuntu. Both projects publish prebuilt binaries on GitHub, so I download and extract them directly:

There are a few parameters worth calling out:

I could have piped each project's install script to sh instead, but those scripts can modify shell configuration files, which would fight with my dotfiles.

This module manages git checkouts. My dotfiles live in a public GitHub repo, and its setup.sh script symlinks each config into ~/.config.

  • name: Clone dotfiles ansible.builtin.git: repo: https://github.com/ryancheley/dotfiles.git dest: "/home/{{ username }}/code/dotfiles" version: main become: true become_user: "{{ username }}"
  • name: Link dotfiles ansible.builtin.command: ./setup.sh args: chdir: "/home/{{ username }}/code/dotfiles" creates: "/home/{{ username }}/.config/fish" become: true become_user: "{{ username }}"

The become_user parameter runs both tasks as the user created earlier, so the files belong to them rather than root. Since version is set to main, each run pulls the latest commits, and because setup.sh creates symlinks the changes show up immediately.

The second task uses the command module from earlier. The creates parameter means setup.sh only runs once, when ~/.config/fish doesn't exist yet.

My first version of this playbook used Ansible's community.general.ufw module to only allow SSH over my tailnet. I took it out for two reasons. First, I already manage my server firewalls with OpenTofu, and having two tools in charge of who can reach port 22 is a recipe for confusion. Second, Docker writes its own firewall rules, so any port a container publishes skips UFW entirely, which matters on a Coolify server.

A firewall is part of building the house, not furnishing it, so it belongs in OpenTofu:

resource "hcloud_firewall" "tailnet_only" { name = "tailnet-only-firewall" rule { direction = "in" protocol = "icmp" source_ips = ["0.0.0.0/0", "::/0"] } rule { description = "Tailscale direct connections" direction = "in" port = "41641" protocol = "udp" source_ips = ["0.0.0.0/0", "::/0"] } rule { direction = "in" port = "80" protocol = "tcp" source_ips = ["0.0.0.0/0", "::/0"] } rule { direction = "in" port = "443" protocol = "tcp" source_ips = ["0.0.0.0/0", "::/0"] } }

There's no rule for port 22. SSH over Tailscale travels inside an encrypted WireGuard tunnel, so the cloud firewall never sees it as SSH traffic.

The catch is that Ansible needs public SSH the first time, before the server has joined my tailnet. So a new server goes through three steps:

From then on, the server is only reachable over SSH through my tailnet. Since Coolify manages servers over SSH, the server also needs to be added to Coolify using its tailnet address.

When you put it all together, this is what my full playbook looks like:

  • name: Bootstrap server hosts: lab vars:

Injected by op run --env-file=.env; nothing user-specific lives in the repo.

username: "{{ lookup('env', 'BOOTSTRAP_USERNAME') }}" user_password: "{{ lookup('env', 'BOOTSTRAP_PASSW

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →