You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确将Ansible中register的STS角色凭证值作为角色环境变量传递?

解决Ansible跨Play传递STS凭证作为环境变量的问题

这个错误的核心原因是Ansible的变量作用域限制:你在第一个针对localhost的Play中注册的assumed_role变量,默认只能在这个Play内部以及针对localhost的任务中访问。后面的Configure New Linux Instance和Configure New Windows Instance Play是针对其他主机组的,无法直接获取到localhost上的注册变量,所以才会提示assumed_role未定义。

这里有两种简单可靠的解决方案,你可以任选其一:

方法1:使用set_fact创建全局可用的凭证变量

在第一个Play的Assume Credentials任务之后,添加一个set_fact任务,把STS凭证存储为全局事实变量,这样所有后续Play都能直接引用:

- name: Create Instance
  hosts: localhost
  gather_facts: false
  connection: local
  tasks:
    # ... 你的其他任务 ...
    - name: Assume Credentials
      sts_assume_role:
        region: "{{ target_region }}"
        role_arn: "{{ awsarnrole }}"
        role_session_name: "AWXBuildServer"
      register: assumed_role

    # 新增:将STS凭证转为全局事实
    - name: Make STS credentials available globally
      set_fact:
        aws_sts_access_key: "{{ assumed_role.sts_creds.access_key }}"
        aws_sts_secret_key: "{{ assumed_role.sts_creds.secret_key }}"
        aws_sts_session_token: "{{ assumed_role.sts_creds.session_token }}"
      delegate_to: localhost
      run_once: true
    # ... 你的其他任务 ...

然后在后续Play的environment中引用这些全局变量:

- name: Configure New Linux Instance
  hosts: new_launch_linux
  gather_facts: true
  roles:
    - systemupdates
    - generalostasks
    - networkconfig
    - appgroup
  environment:
    AWS_ACCESS_KEY: "{{ aws_sts_access_key }}"
    AWS_SECRET_ACCESS_KEY: "{{ aws_sts_secret_key }}"
    AWS_SECURITY_TOKEN: "{{ aws_sts_session_token }}"

如果Windows实例也需要这些凭证,同样在对应的Play中添加相同的environment配置即可。

方法2:直接通过hostvars引用localhost的注册变量

如果你不想额外创建新变量,可以直接通过hostvars这个特殊变量来访问localhost上的assumed_role注册结果,省去set_fact的步骤:

- name: Configure New Linux Instance
  hosts: new_launch_linux
  gather_facts: true
  roles:
    - systemupdates
    - generalostasks
    - networkconfig
    - appgroup
  environment:
    AWS_ACCESS_KEY: "{{ hostvars['localhost'].assumed_role.sts_creds.access_key }}"
    AWS_SECRET_ACCESS_KEY: "{{ hostvars['localhost'].assumed_role.sts_creds.secret_key }}"
    AWS_SECURITY_TOKEN: "{{ hostvars['localhost'].assumed_role.sts_creds.session_token }}"

注意事项

  • 这两种方法都能解决跨Play的变量传递问题,方法1的变量名更简洁,方法2更直接无需额外任务。
  • 因为这些AWS凭证是敏感数据,AWX默认会在日志中屏蔽这类敏感变量,但建议你确认AWX的日志配置,避免泄露凭证。

内容的提问来源于stack exchange,提问作者Brian G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:22:41