【问题标题】:Running a Terraform command via Airflow operator通过 Airflow 操作符运行 Terraform 命令
【发布时间】:2021-02-15 15:09:58
【问题描述】:

我在 Cloud Composer (composer-1.14.2-airflow-1.10.14) 上运行 Apache Airflow。我想使用 Terraform 来创建基础设施,但我找不到任何运营商来做这件事。作为一种解决方法,我正在使用这样的 BashOperator:

create_vm=BashOperator(
    task_id='create_cluster',
    bash_command=f'''
        sudo apt-get update -y && \
        sudo apt-get install software-properties-common -y && \
        sudo apt-get update -y && \
        curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add - && \
        sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main" && \
        sudo apt-get update && sudo apt-get install terraform && \
        cd /home/airflow/gcs/.../ && \
        terraform init && \
        terraform plan -out /home/airflow/gcs/.../plantf && \
        terraform init && \
        terraform apply /home/airflow/gcs/.../plantf
    ''',

    dag=dag)

这真的不像是最佳实践。是否有推荐的方法通过 Airflow 操作符运行 Terraform 命令?

【问题讨论】:

    标签: terraform airflow google-cloud-composer


    【解决方案1】:

    经过多次哀号和咬牙切齿,我能够完成您想要做的事情。我使用的是 Docker,但希望可以应用相同的原则。

    1. 我编写了一个 shell 脚本来覆盖 Airflow worker 入口点,这样我就可以安装和初始化 Terraform。
    #!/bin/bash
    
    terraform_version="0.14.8"
    terraform_installer_zipfile="terraform_${terraform_version}_linux_amd64.zip"
    
    curl -O -L https://releases.hashicorp.com/terraform/${terraform_version}/${terraform_installer_zipfile}
    python3 unzip-terraform.py ${terraform_installer_zipfile}
    
    chmod +x terraform
    
    ./terraform init
    
    /entrypoint ${1} ${2}
    
    1. Airflow官方镜像有权限限制,无法安装解压。所以我改用了python脚本。 (在 #1 的脚本中解压缩 terraform.py)
    import sys
    import zipfile
    
    with zipfile.ZipFile(sys.argv[1], 'r') as terraformInstaller:
        terraformInstaller.extractall()
    
    1. 我在第 4 步中编写了另外两个供 BashOperators 使用的 shell 脚本。(我正在使用它来设置 GCP 计算资源)。
    #!/bin/bash
    
    cd /opt/airflow
    
    chmod +x terraform
    
    ./terraform plan -out=gcp-test
    
    ./terraform apply "./gcp-test"
    
    #!/bin/bash
    
    cd /opt/airflow
    
    chmod +x terraform
    
    ./terraform destroy -auto-approve
    
    1. 我使用 BashOperators 来建立/拆除计算资源。
    terraform_build_task = BashOperator(
        task_id = 'terraform_build_task',
        dag = dag,
        bash_command =  '/opt/airflow/terraform-plan-apply.sh '
    )
    
    terraform_destroy_task = BashOperator(
        task_id = 'terraform_destroy_task',
        dag = dag,
        bash_command =  '/opt/airflow/terraform-plan-destroy.sh '
    )
    

    效果很好。另外,我应该指出bash_command 值中的尾随空格是故意的。没有它,Airflow 将尝试应用 Jinja 模板,但它会失败。

    【讨论】:

    • 欢迎来到 StackOverflow,感谢您参与讨论。今后,请不要发布实际上并不能回答问题的答案 - 请将其作为对问题的评论(选择添加评论)。 Read more.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    相关资源
    最近更新 更多