3

我正在尝试使用 ec2 模块在 AWS 上配置新机器并在本地更新我的主机文件,以便下一个任务已经使用主机文件。

因此,配置不是问题,甚至是本地主机文件的创建:

- name: Provision a set of instances
      ec2:
         key_name: AWS
         region: eu-west-1
         group: default
         instance_type: t2.micro
         image: ami-6f587e1c # For Ubuntu 14.04 LTS use ami-b9b394ca # For Ubuntu 16.04 LTS use ami-6f587e1c
         wait: yes
         volumes:
          - device_name: /dev/xvda
            volume_type: gp2
            volume_size: 50
            wait: true
         count: 2
         vpc_subnet_id: subnet-xxxxxxxx
         assign_public_ip: yes
         instance_tags:
            Name: Ansible
      register: ec2

    - name: Add all instance private IPs to host group
      add_host:
          hostname: "{{ item.private_ip }}"
          ansible_ssh_user: ubuntu
          groups: aws
      with_items: "{{ ec2.instances }}"

    - local_action: file path=./hosts state=absent
      ignore_errors: yes

    - local_action: file path=./hosts state=touch

    - local_action: lineinfile line="[all]" insertafter=EOF dest=./hosts

    - local_action: lineinfile line="{{ item.private_ip }}  ansible_python_interpreter=/usr/bin/python3" insertafter=EOF dest=./hosts
      with_items: "{{ ec2.instances }}"

    - name: Wait for SSH to come up
      wait_for:
          host: "{{ item.private_ip }}"
          port: 22
          delay: 60
          timeout: 600
          state: started
      with_items: "{{ ec2.instances }}"

    - name: refreshing inventory cache
      meta: refresh_inventory

- hosts: all
  gather_facts: False
  tasks:
    - command: hostname -i

但是,下一个任务是 hostname -i 的简单打印(仅用于测试)失败,因为它在 Ubuntu 16.04 LTS Python 2.7(有 python3)上找不到为此,在我的动态主机文件中添加以下行:

ansible_python_interpreter=/usr/bin/python3

但似乎 ansible 忽略了它并直接进入缺少的 python 2.7。

我试图重新加载库存文件

meta: refresh_inventory

但这也无济于事。我究竟做错了什么 ?

4

1 回答 1

2

我不确定为什么刷新不起作用,但我建议在add_host部分中设置它,它需要任何变量。

- name: Add all instance private IPs to host group
  add_host:
      hostname: "{{ item.private_ip }}"
      ansible_ssh_user: ubuntu
      groups: aws
      ansible_python_interpreter: "/usr/bin/python3"
  with_items: "{{ ec2.instances }}"

我也发现用这个任务进行调试很有用

- debug: var=hostvars[inventory_hostname]
于 2017-12-20T02:27:26.110 回答