You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过Terraform在Ubuntu系统执行Shell命令?需提前完成初始配置

在Ubuntu中通过Terraform执行Shell命令及前置配置指南

一、通过Terraform执行Shell命令的实现方式

Terraform支持通过provisioner模块在Ubuntu环境中执行Shell命令,常用的有两种场景:

1. 本地执行(local-exec)

用于在运行Terraform的本地Ubuntu机器上执行命令,适合完成本地文件操作、环境初始化等任务:

resource "null_resource" "local_shell_task" {
  provisioner "local-exec" {
    command = "echo 'Terraform local execution log' >> ~/terraform_ops.log && mkdir -p ~/terraform_work_dir"
    interpreter = ["bash", "-c"]
  }
}
  • interpreter指定用bash解释器解析命令
  • command字段支持多命令拼接(用&&分隔),按顺序执行

2. 远程执行(remote-exec)

用于在远程Ubuntu主机上执行命令,需配合SSH连接配置,适合管理远程服务器的软件安装、服务启停等操作:

resource "null_resource" "remote_shell_task" {
  provisioner "remote-exec" {
    inline = [
      "sudo apt update -y",
      "sudo apt install -y nginx git",
      "sudo systemctl enable --now nginx"
    ]

    connection {
      type        = "ssh"
      user        = "ubuntu"
      private_key = file("~/.ssh/id_rsa")
      host        = "192.168.1.20" # 替换为你的远程主机IP
    }
  }
}
  • inline是待执行的命令列表,按顺序运行
  • connection块配置SSH连接参数,需确保本地主机能无密码访问远程主机

二、运行Terraform脚本前的初始配置

1. 安装Terraform

在Ubuntu系统中安装官方稳定版:

# 添加HashiCorp GPG密钥
wget -O- https://apt.releases.hashicorp.com/gpg | gpg --dearmor | sudo tee /usr/share/keyrings/hashicorp-archive-keyring.gpg
# 添加HashiCorp软件源
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 terraform -y
# 验证安装
terraform --version

2. 配置SSH访问(仅远程执行场景需要)

  • 生成SSH密钥对(无密码):
    ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/id_rsa
    
  • 将公钥复制到远程Ubuntu主机:
    ssh-copy-id ubuntu@192.168.1.20 # 替换为远程用户和IP
    
  • 测试无密码SSH连接:
    ssh ubuntu@192.168.1.20
    

3. 初始化Terraform工作目录

  • 创建并进入工作目录:
    mkdir terraform-shell-demo && cd terraform-shell-demo
    
  • 初始化Terraform(下载依赖的provider):
    terraform init
    

4. 配置sudo权限(执行特权命令时需要)

  • 本地执行:允许当前用户无密码sudo,编辑sudoers文件:
    sudo visudo
    
    添加行:your_username ALL=(ALL) NOPASSWD: ALL(替换为你的系统用户名)
  • 远程执行:在远程Ubuntu主机上完成同样的sudo配置,避免命令执行时需要输入密码

内容的提问来源于stack exchange,提问作者Peter Penzov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 13:25:40