簡體   English   中英

Airflow BashOperator - 使用與其 pod 角色不同的角色

[英]Airflow BashOperator - Use different role then its pod role

作為在 BashOperator 中運行的 bash 腳本的一部分,我嘗試運行以下命令:

aws cli ls s3://bucket
aws cli cp ... ...

腳本成功運行,但是aws cli命令返回錯誤,表明aws cli沒有以所需的權限運行(如airflow-worker-node角色中定義的那樣)

調查錯誤:

  1. 我已經將運行 pod 的awscli中的 awscli 升級到 2.4.9 版(我知道舊版本的awscli不支持基於aws role授予的權限訪問 s3

  2. 我已經使用 BashOperator 調查了運行我的 bash_script 的 pod:

  • 使用 k9s 和 D(描述)命令:

    • 我看到 ARN_ROLE 定義正確
  • 使用 k9s 和 s (shell) 命令:

    • 我看到 pod 環境變量是正確的。
    • aws cli使用所需的權限,可以根據需要訪問s3
    • aws sts get-caller-identity - 報告了正確的角色 ( airflow-worker-node )
  1. 將上述命令作為在BashOperator中執行的 bash 腳本的一部分運行給了我不同的結果:

    • 運行env顯示有限數量的環境變量
    • aws cli返回與權限相關的錯誤。
    • aws sts get-caller-identity - 報告 eks 角色 ( eks-worker-node )

如何在我的 BashOperator bash-script 中授予aws cli所需的權限?

查看 BashOperator 源代碼,我注意到以下代碼:

https://github.com/apache/airflow/blob/main/airflow/operators/bash.py

def get_env(self, context):
    """Builds the set of environment variables to be exposed for the bash command"""
    system_env = os.environ.copy()
    env = self.env
    if env is None:
        env = system_env
    else:
        if self.append_env:
            system_env.update(env)
            env = system_env

以及以下文檔:

:param env: If env is not None, it must be a dict that defines the
    environment variables for the new process; these are used instead
    of inheriting the current process environment, which is the default
    behavior. (templated)
:type env: dict
:param append_env: If False(default) uses the environment variables passed in env params
    and does not inherit the current process environment. If True, inherits the environment variables
    from current passes and then environment variable passed by the user will either update the existing
    inherited environment variables or the new variables gets appended to it
:type append_env: bool

如果 bash 操作符輸入環境變量為無,則復制父進程的環境變量。 就我而言,我提供了一些環境變量,因此它沒有將父進程的環境變量復制到 chid 進程中 - 這導致子進程(BashOperator 進程)使用 eks-worker-node 的默認 arn_role。

簡單的解決方案是在 BashOperator() 中設置以下標志: append_env=True這會將env所有現有的環境變量添加到我手動添加的環境變量中。

我發現在我正在運行的版本(2.0.1)中它不受支持(它在以后的版本中受支持)。 作為臨時解決方案,我將**os.environ - 添加到BashOperator env參數中:

return BashOperator(
    task_id="copy_data_from_mcd_s3",
    env={
        "dag_input": "{{ dag_run.conf }}",
        ......
        **os.environ,
    },
    # append_env=True,- should be supported in 2.2.0
    bash_command="utils/my_script.sh",
    dag=dag,
    retries=1,
)

哪個解決了問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM