【问题标题】:How to pass ec2 variable from one ansible host to another如何将ec2变量从一个ansible主机传递到另一个
【发布时间】:2016-12-30 15:19:44
【问题描述】:

我想将我新创建的 ec2 实例的“private_dns_name”传递给我的 ansible 剧本中的其他主机。我曾尝试使用 set_fact 模块来定义变量,但没有运气!这是 host1 的 ansible playbook 条目

- name: new EC2 instance
   hosts: host1   
  tasks:
    - name: Launch the new EC2 Instance
      ec2:
       aws_access_key: "{{ aws_id }}"
       aws_secret_key: "{{ aws_key }}"
       group_id: "{{ security_group_id }}"
       instance_type: "{{ instance_type }}"
       image: "{{ image }}"
       key_name: "{{ ssh_keyname }}"
       wait: yes
       wait_timeout: 900
       region: "{{ region }}"
       count: 1
       instance_tags:
         Name: Prod-Engineering
      register: ec2
    - name: Register public DNS fact
      set_fact: public_dns= "{{ item.private_dns_name }}"
      with_items: ec2.instances

在定义 set_fact 之后,我使用下面的示例代码将 private_dns_name 抓取到我的另一个 host2:

 - hosts: host2
   become: yes
   tasks:
    - command: ipa host-add "{{ public_dns}}" --password=xxxxx

但我在执行我的剧本时收到 public_dns variable not defined 错误。如何从新创建的 ec2 实例中检索/传递变量到另一个主机/ec2 实例?

【问题讨论】:

    标签: amazon-ec2 ansible ansible-2.x


    【解决方案1】:

    使用 ansible magic variables 访问其他主机的事实:

    - hosts: host2
      become: yes
      tasks:
        - command: ipa host-add "{{ hostvars['host1']['public_dns'] }}" --password=xxxxx
    

    【讨论】:

    • 感谢 Konstantin,但现在我的剧本中出现“'ansible.vars.hostvars.HostVars object' has no attribute”错误。我尝试添加
    • 感谢 Konstantin,但现在我收到“'ansible.vars.hostvars.HostVars object' has no attribute”错误。我尝试在 host1 下添加 - debug: var=hostvars & - debug: msg= "{{ hostvars }}" 但也没有运气。这里可能是什么问题?再次感谢!
    • @DeepakPrasad 首先你不能在这个符号的等号后使用空格——使用debug: msg="{{ hostvars }}"。 set_fact: public_ip= ... public_ip 中的这个空间将始终为空。但是,如果您有 hostvars 未定义,则您的设置完全有问题 - 它应该始终可用。
    • 我正在使用 ansible 2.1.1.0,它并不真正关心 msg= 之后的空间或没有空间,它不起作用并最终出现错误:'ansible.vars.hostvars. HostVars 对象'没有属性
    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    • 2018-11-04
    • 2014-01-03
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多