Ansible:如何为单个任务指定ssh密钥?

时间:2016-10-18 00:39:09

标签: ssh amazon-ec2 ansible

我有一个创建和ec2实例的playbook,将几个文件复制到实例,然后在实例上运行一些shell命令。

问题是我希望能够指定anssh用于我正在运行的副本和shell任务的ssh密钥,并确保它不会尝试将此密钥用于在localhost上运行的其他任务。这是我的剧本:

---
- hosts: localhost
  connection: local
  gather_facts: false

  vars:
    # CentOS 7 x86_64 Devel AtomicHost EBS HVM 20150306_01 (ami-07e6c437)
    # for us-west-2
    - ami: 'ami-07e6c437'
    - key_pair: 'my-key'

  tasks:

    - name: Create a centos server
      ec2:
        region: 'us-west-2'
        key_name: '{{ key_pair }}'
        group: default
        instance_type: t2.micro
        image: '{{ ami }}'
        wait: true
        exact_count: 1
        count_tag:
          Name: my-instance
        instance_tags:
          Name: my-instance
      register: ec2

    # shows the json data for the instances created
    - name: Show ec2 instance json data
      debug:
        msg: "{{ ec2['tagged_instances'] }}"

    - name: Wait for SSH to come up
      wait_for: host={{ ec2['tagged_instances'][0]['public_ip'] }} port=22 delay=1 timeout=480 state=started

    - name: Accept new ssh fingerprints                                       
      shell: ssh-keyscan -H "{{ ec2['tagged_instances'][0]['public_ip'] }}" >> ~/.ssh/known_hosts          

    # THE TASKS I NEED HELP ON
    - name: Copy files over to ec2 instance
      remote_user: centos 
      copy: src={{ item }} dest=/home/centos/ mode=600
      with_fileglob:
        - my-files/*
      delegate_to: "{{ ec2['tagged_instances'][0]['public_ip'] }}"   

    # THE TASKS I NEED HELP ON
    - name: run commands
      remote_user: centos                                        
      shell: "{{ item }}"
      delegate_to: "{{ ec2['tagged_instances'][0]['public_ip'] }}"
      with_items:
        - "sudo yum update -y"
        - "sudo yum install nmap ruby"
      ignore_errors: true 

1 个答案:

答案 0 :(得分:1)

是的,我同意@techraf。但是您发布的问题的答案是您必须动态更改您配置的新实例的库存,然后在该新主机上运行远程ansible播放。因此,您可以在第一次播放结束时添加此内容:

    - local_action:
        module: add_host
        hostname: newhost
        ansible_host: "{{ ec2['tagged_instances'][0]['public_ip'] }}"
        ansible_user: centos
        ansible_ssh_private_key_file: /path/to/keyfile

###### New play
- name: Configure my new instance!
  hosts: newhost
  tasks:
    # THE TASKS I NEED HELP ON
    - name: Copy files over to ec2 instance
      copy: src={{ item }} dest=/home/centos/ mode=600
      with_fileglob:
        - my-files/*
    # Use the yum module here instead, much easier
    - name: run commands
      shell: "{{ item }}"
      with_items:
        - "sudo yum update -y"
        - "sudo yum install nmap ruby"
      ignore_errors: true 

编辑:添加,您始终可以使用以下方式设置ssh主机密钥:

- set_fact: ansible_ssh_private_key_file=/path/to/keyfile

需要注意的是,上面的set_fact只会更改当前正在运行的主机的ssh私钥文件(例如,对于上面示例播放中的localhost)。