如何将Jenkins字符串参数转换为TerraformMap变量?

gxwragnw  于 2023-10-17  发布在  Jenkins
关注(0)|答案(1)|浏览(113)

我试图将字符串参数传递给TerraformMap变量,但收到错误“无效数字文字”。当通过terraform apply -var ...传递Jenkins参数时,如何访问TerraformMap中的键和值还不是很清楚
Jenkinsfile:

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
                                """
                            }
                    } 
                }
            }
        }
    }
}

variables.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"
    }
  }
}
fruv7luv

fruv7luv1#

我想出来了!您可以用'vm 1'替换标识第一个map对象的任何值。

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

如果您还想为VM名称添加一个name string参数,它看起来像

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

相关问题