【问题标题】:How can I run an Ansible playbook without hosts specificed?如何在没有指定主机的情况下运行 Ansible 剧本?
【发布时间】:2019-11-15 07:50:34
【问题描述】:

我正在编写一个脚本,它启动 X 个 EC2 AWS 实例,然后在它们上安装一些软件(apt 包和 pip 模块)。当我运行我的 playbook 时,它会在我的本地系统上执行 shell 命令,因为除非我指定主机并放置 localhost,否则 Ansible 不会运行。

在 playbook 中,我尝试在顶层指定“hosts: all”,但这只会让 playbook 运行一秒钟而不做任何事情。

playbook.yml

- name: Spin up spot instances
  hosts: localhost
  connection: local
  vars_files: ansible-vars.yml
  tasks:
    - name: create {{ spot_count }} spot instances with spot_price of ${{ spot_price }}      
      local_action:
        module: ec2
        region: us-east-2
        spot_price:  '{{ spot_price }}'
        spot_wait_timeout: 180
        keypair: My-keypair
        instance_type: t3a.nano
        image: ami-0f65671a86f061fcd
        group: Allow from Home
        instance_initiated_shutdown_behavior: terminate
        wait: yes
        count:  '{{ spot_count }}'
      register: ec2

    - name: Wait for the instances to boot by checking the ssh port
      wait_for: host={{item.public_ip}} port=22 delay=15 timeout=300 state=started
      with_items: "{{ ec2.instances }}"

    - name: test whoami
      args:
        executable: /bin/bash
      shell: whoami
      with_items: "{{ ec2.instances }}"

    - name: Update apt
      args:
        executable: /bin/bash
      shell: apt update
      become: yes
      with_items: "{{ ec2.instances }}"

    - name: Install Python and Pip
      args:
        executable: /bin/bash
      shell: apt install python3 python3-pip -y        
      become: yes
      with_items: "{{ ec2.instances }}"

    - name: Install Python modules
      args:
        executable: /bin/bash
      shell: pip3 install bs4 requests
      with_items: "{{ ec2.instances }}"

ansible-vars.yml

ansible_ssh_private_key_file: ~/.ssh/my-keypair.pem
spot_count: 1
spot_price: '0.002'
remote_user: ubuntu

EC2 实例创建得很好,“等待 SSH”任务有效,但 shell 任务在我的本地系统而不是远程主机上运行。

我如何告诉 Ansible 在不使用主机文件的情况下连接到 EC2 实例,因为我们是动态创建的?

【问题讨论】:

  • 您必须使用add_host module 来注册您动态创建的主机并将您的shell 任务的下一次播放定位到它们。
  • @Zeitounator 你能发布一个例子吗?我尝试使用我找到的示例,但我真的不知道该放在哪里。

标签: ansible


【解决方案1】:

如果可行,你可以试试这个。

- name: test whoami
      args:
        executable: /bin/bash
      shell: whoami
      delegate_to: "{{ item }}"
      with_items: "{{ ec2.instances }}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    相关资源
    最近更新 更多