【问题标题】:Jenkinsfile - add private key credential to terraformJenkinsfile - 将私钥凭证添加到 terraform
【发布时间】:2018-09-11 18:51:56
【问题描述】:

作为我的 Jenkinsfile 的一部分,我正在尝试加载我在 Jenkins 机器上拥有的秘密文件,并将其用作变量以传递到我的 terraform 脚本中。这个 terraform 脚本正在 ssh'ing 到我新配置的 ansible 服务器并生成一个 Ansible 清单。问题是将私钥文件作为变量加载到 terraform 脚本中,以从我在 Jenkins 中的临时构建中创建 ssh 连接。

如您所见,加载凭据并存储在 terraform var (TF_VAR_private_key) 中,但我无法将其加载到我的 main.tf terraform 脚本中。

非常感谢任何建议或帮助。

詹金斯文件

stages {
    stage('Provision Infrastructure') {
        steps {
            // credentialsId loading private key and storing in var
            withCredentials([file(credentialsId: 'ec2user.pem', variable: 'TF_VAR_private_key'),
            [
                $class           : 'AmazonWebServicesCredentialsBinding',
                credentialsId    : "aws_credentials",
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
            ]])
            { sh """               
                terraform version
                cd ${TERRAFORM_DIR}
                terraform init
                terraform plan
                terraform apply -input=false -auto-approve
            """ }
        }
    }

main.tf

resource "null_resource" "inventories" {

  triggers {
    template = "${template_file.inventory.rendered}"
  }
  connection {
    type = "ssh"
    host = "${element(aws_instance.ansible.*.private_ip, 0)}"
    user = "ec2-user"
    private_key = "${file("${var.private_key}")}"
    agent = false
    timeout = "1m"
  }

  provisioner "remote-exec" {
    inline = [
      "echo '${template_file.inventory.rendered}' > /tmp/inventory"
    ]
  }
}

错误:

无法运行 remote-exec,因为找不到私钥文件。

【问题讨论】:

  • 为什么不使用-var标志?
  • 我敢打赌这是因为 Jenkins 没有将该环境变量传递给 Terraform。您是否尝试将 env var 注入到构建步骤中?

标签: jenkins-pipeline terraform


【解决方案1】:

我尝试了几种方法,这是有效的:

詹金斯文件

withCredentials([sshUserPrivateKey(
    credentialsId: 'e4dd944e-5fef-4109-801c-b478d41af2d7',
    keyFileVariable: 'SSH_KEY')])
{
    sh 'cp "$SSH_KEY" files/jenkins-aws.pem'
    sh 'terraform plan -out tfplan'
}

您需要将凭证文件复制到 terraform 可以在工作区中访问的某个位置。然后在您的 terraform 中正常使用它:

main.tf

variable "ssh_private_key_file" {
  default = "files/jenkins-aws.pem"
}

locals {
  ssh_private_key_content = file(var.ssh_private_key_file)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-07
    • 2023-03-19
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2012-01-15
    相关资源
    最近更新 更多