如何将Jenkins字符串参数转换为Terraform地图变量?

问题描述 投票:0回答:2

我正在尝试将字符串参数传递给 Terraform 地图变量,但收到错误“无效数字文字”。通过

terraform apply -var ...

传递 Jenkins 参数时,如何访问 Terraform 地图中的键和值还不太清楚

詹金斯文件:

pipeline {
    agent any

    parameters {
        string(name: 'IP1', defaultValue: '', description: 'Enter first IP address')
    }
    
    stages {
        stage('Git Checkout') {
            steps {
                git branch: 'branch1', credentialsId: '', url: 'http://<redacted>.git'
            }
        }
        stage('Deploy Terraform') {
            steps {
                script {
                        dir('Linux') {
                                sh """
                                terraform init
                                terraform plan
                                terraform apply -var 'vms=${params.IP1}' \
                                --auto-approve
                                """
                            }
                    } 
                }
            }
        }
    }
}

变量.tf

variable "vm_map" {
  type = map(object({
    name = string
    ip   = string
  }))
  default = {
    "first" = {
      name = "ubuntu-jenkins1"
      ip   = "172.30.100.160"
    }
    "second" = {
      name = "ubuntu-jenkins2"
      ip   = "172.30.100.161"
    }
    "third" = {
      name = "ubuntu-jenkins3"
      ip   = "172.30.100.162"
    }
  }
}
jenkins terraform jenkins-pipeline jenkins-groovy infrastructure-as-code
2个回答
1
投票

我想通了!您可以将“vm1”替换为标识第一个地图对象的任何值。

terraform apply -var vms='''{vm1: {name: "ubuntu",ip: "${params.IP1}"}}''' --auto-approve

如果您还想为虚拟机名称添加名称字符串参数,它看起来像

terraform apply -var vms='''{vm1: {name: "${params.VM_NAME1}",ip: "${params.IP1}"}}''' --auto-approve

这是适用于多个虚拟机的 terraform

terraform apply -var 'vm_map={"first": {"name": "ubuntu-jenkins1", "ip": "172.30.100.160"}, \
      "second": {"name": "ubuntu-jenkins2", "ip": "172.30.100.161"}, \
      "third": {"name": "ubuntu-jenkins3", "ip": "172.30.100.162"}}' --auto-approve

-1
投票

这是适用于多个虚拟机的 terraform

terraform apply -var 'vm_map={"first": {"name": "ubuntu-jenkins1", "ip": "172.30.100.160"}, \
                                                          "second": {"name": "ubuntu-jenkins2", "ip": "172.30.100.161"}, \
                                                          "third": {"name": "ubuntu-jenkins3", "ip": "172.30.100.162"}}' --auto-approve
© www.soinside.com 2019 - 2024. All rights reserved.