我正在写一个剧本,它旋转X个EC2 AWS实例,然后在它们上安装一些软件(apt软件包和pip模块)。当我运行剧本时,它将在我的本地系统上执行shell命令,因为除非指定主机并放置localhost,否则Ansible不会运行。
在剧本中,我尝试在顶层指定“主机:所有”,但这只会使剧本运行一秒钟而不执行任何操作。
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,我如何告诉Ansible在不使用hosts文件的情况下连接到EC2实例?
答案 0 :(得分:0)
如果可以的话,您可以尝试一下。
- name: test whoami
args:
executable: /bin/bash
shell: whoami
delegate_to: "{{ item }}"
with_items: "{{ ec2.instances }}"