将Jenkins中的AWS凭据传递到Ansible剧本中

nsc4cvqm  于 2022-11-02  发布在  Jenkins
关注(0)|答案(1)|浏览(166)

我试图将我存储在jenkins中的aws creds传递到ansible playbook中,但它似乎没有接受它。我做过研究,似乎每个人都将他们的creds存储在jenkins文件中。是否可以将变量传递到ansible playbook中?下面是我目前的情况
Jenkins Creds
Jenkins锉

pipeline {
    agent any
    stages {
        stage('GIT Code Checkout'){
           steps{
               git branch: 'ansible', credentialsId: 'test-pipeline', url: 'https://github.com/newbtech'
           }
    environment{
        AWS_ACCESS_KEY_ID = credentials('aws-key')
        AWS_SECRET_ACCESS_KEY = credentials('aws_secret_access_key')
        }
        stage('Run Tools Playbook'){
           steps{
               ansiblePlaybook credentialsId: 'root-key', 
               disableHostKeyChecking: true, installation: 'ansible', 
               extras: "-e HOST=${SERVER}", 
               inventory: 'ansible/host.inv', 
               playbook: 'ansible/cstest.yml'                
           }
        }
    }
}

Ansible行动手册

---
- hosts: "{{ HOST }}"
  tasks:
    - name: "S3 Pull - Ubunutu"
      aws_s3:
        aws_access_key: "aws-key"
        aws_secret_key: "aws_secret_access_key"
        bucket: "images"
        object: "ubuntu.deb"
        dest: "/tmp/ubuntu.deb"
        mode: get
      when: ansible_facts['os_family'] == "Debian"
      vars:
         ansible_python_interpreter: /usr/bin/python3
jaql4c8m

jaql4c8m1#

使用Credentials Binding插件
我已经尝试使用这个插件的 * 管道语法 * 的代码段生成器,但它对我一点帮助都没有。
在管道中希望凭据可用的步骤下定义一个withCredentials块:

withCredentials(
[[
    $class: 'AmazonWebServicesCredentialsBinding',
    accessKeyVariable: 'AWS_ACCESS_KEY_ID',
    credentialsId: 'aws',  # ID of AWS credentials in Jenkins
    secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
]])

在您的管道中:

pipeline {
  agent any

  stages {
    stage ('Git checkout')
    {
      steps
      {
        git branch: 'ansible', credentialsId: 'test-pipeline', url: 'https://github.com/newbtech'
      } 
    }
    stage('Run Tools Playbook')
    {
      steps
      {
        withCredentials(
            [[
                $class: 'AmazonWebServicesCredentialsBinding',
                accessKeyVariable: 'AWS_ACCESS_KEY_ID',
                credentialsId: 'aws-key',
                secretKeyVariable: 'AWS_SECRET_ACCESS_KEY'
            ]])
        {
          ansiblePlaybook credentialsId: 'root-key', 
          disableHostKeyChecking: true, installation: 'ansible', 
          extras: "-e HOST=${SERVER}", 
          inventory: 'ansible/host.inv', 
          playbook: 'ansible/cstest.yml' 
        }
      }
    }
  }
}

然后,您可以在行动手册中定义凭据,如下所示:

---
- hosts: "{{ HOST }}"
  tasks:
  - name: "S3 Pull - Ubunutu"
    aws_s3:
      aws_access_key: "AWS_ACCESS_KEY_ID"
      aws_secret_key: "AWS_SECRET_ACCESS_KEY"
      bucket: "images"
      object: "ubuntu.deb"
      dest: "/tmp/ubuntu.deb"
      mode: get
    when: ansible_facts['os_family'] == "Debian"
    vars:
       ansible_python_interpreter: /usr/bin/python3

相关问题