如何在 terraform 中运行 sudo 命令? [英] How to run sudo commands in terraform?
问题描述
我的问题和这个 git hub 帖子类似,但很遗憾没有解决:
My question is similar to this git hub post, but unfortunately it is unsolved:
https://github.com/hashicorp/terraform/issues/550
我想要一种简单的方法来为在我的 terraform 脚本的 provisioner "remote-exec" { }
块中运行的命令授予 sudo 权限.
I want a simple way to give sudo privileges to the commands run in the provisioner "remote-exec" { }
block of my terraform scripts.
我来自具有 sudo: yes
选项的 ansible 背景,该选项允许 ansible 运行的任何命令在使用 --ask-sudo-pass 时以 sudo 权限运行命令
在我的 ansible-playbook 运行命令中是可选的.我想在我的 terraform 脚本的 provisioner "remote-exec"
块中做类似的事情.
I am coming from an ansible background that has the sudo: yes
option that allows any commands ansible runs to run commands with sudo privileges when using the --ask-sudo-pass
optional in my ansible-playbook run commands. I would like to do something like that in the provisioner "remote-exec"
block of my terraform script.
这是我要运行的 provisioner "remote-exec"
块:
Here is the provisioner "remote-exec"
block I want to run:
provisioner "remote-exec" {
inline = [
"sudo apt-get update",
"sudo apt-get install -y curl"
]
}
当我在 terraform apply
中运行此命令时,我看到此命令的输出中出现以下几行:
When I run this in my terraform apply
I see the following lines appear in the output of this command:
openstack_compute_instance_v2.test.0 (remote-exec): [sudo] password for myUserName:
openstack_compute_instance_v2.test.1 (remote-exec): [sudo] password for myUserName:
openstack_compute_instance_v2.test.2 (remote-exec): [sudo] password for myUserName:
然后它给了我无数的这些:
Then it just gives me an infinite number of these:
openstack_compute_instance_v2.test.0: Still creating...
openstack_compute_instance_v2.test.1: Still creating...
openstack_compute_instance_v2.test.2: Still creating...
那么我该如何解决这个问题并让 terraform 运行 sudo 命令?
So how do I fix this and let terraform run sudo commands?
注意:我的 provisioner "remote-exec"
块的连接不能是 root,所以即使这是一个简单的解决方案,它也不是我可以使用的.
Note: The connection for my provisioner "remote-exec"
block cannot be root, so even though that would be a simple solution its not what I can use.
推荐答案
答案是在我的第一个 sudo 命令中使用以下语法:
The answer was to use the following syntax in my first sudo command:
"echo yourPW | sudo -S someCommand"
这绕过了sudo密码提示,直接在命令中输入密码.我已经有我的 sudo 密码作为变量 "${var.pw}"
所以运行我的 sudo 命令很简单,将我的第一个命令更改为:
This bypasses the sudo password prompt and enters the password directly into the command. I already had my sudo password as a variable "${var.pw}"
so running my sudo commands was the simple matter of changing my first command to:
provisioner "remote-exec" {
inline = [
"echo ${var.pw} | sudo -S apt-get update",
"sudo apt-get install -y curl"
]
}
这篇关于如何在 terraform 中运行 sudo 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!