首页 文章

在Ansible / AWS中本地和远程执行角色

提问于
浏览
0

我在Ansible写了两个角色 . 第一个角色(即provision)在具有所需IAM来配置EC2实例的实例上本地执行(见下文):

- name: Provison "{{ count }}" ec2 instances in "{{ region }}"
  ec2:
     key_name: "{{ key_name }}"
     instance_type: "{{ instance_type }}"
     image: "{{ image }}"
 ...
     exact_count: "{{ count }}"
     count_tag: "{{ count_tag }}"
     instance_tags:
 ...
  register: ec2

然后我将私有IP地址添加到主机 .

- name: Add the newly created EC2 instances to the local host file
  local_action: lineinfile
                dest="./hosts"
                regexp={{ item.private_ip }}
                insertafter="[sit]" line={{ item.private_ip }}
  with_items: "{{ ec2.instances }}"

我等待SSH可用 .

- name: Wait for SSH process to be available on "{{ sit }}"
  wait_for:
    host: "{{ item.private_ip }}"
    port: 22
    delay: 60
    timeout: 320
    state: started
  with_items: "{{ ec2.instances }}"

第二个角色(即setupEnv)在'sit'主机上设置环境变量,例如用户/组目录 . 我尝试按顺序运行角色(参见下面的 main.yml playbook):

- hosts: local
  roles:
  connection: local
  gather_facts: false
  user: svc_ansible_lab
  roles:
  - provision

- hosts: sit
  roles:
  connection: ssh
  gather_facts: true
  user: ec2-user
  roles:
  - setupEnv

但是,只有第一个角色在本地主机上执行 . Ansible等待直到SSH在配置的实例上可用,然后该过程结束而不会占用角色setupEnv .

Is there a way I can make sure the second role is executed on the sit hosts after the SSH is available?

1 回答

  • 1

    库存文件不会在播放之间自动重新获取 .

    而不是修改库存文件,请使用add_host module and in-memory inventory .

    - name: Add the newly created EC2 instances to the in-memory inventory
      add_host:
        hostname: "{{ item.private_ip }}"
        groups: sit
      with_items: "{{ ec2.instances }}"
    

    或者,您可以使用meta modulerefresh_inventory 参数强制Ansible重新读取库存文件:

    - meta: refresh_inventory
    

相关问题