如何使用ec2_key模块在Ansible中创建新密钥?

时间:2014-10-17 10:12:12

标签: ansible

我不知道如何在Ansible中使用ec2_key模块。有人可以给我一个如何创建新密钥对的例子吗?

3 个答案:

答案 0 :(得分:9)

工作示例:

- name: Create an EC2 key
  ec2_key:
    name: "mykey"
    region: "eu-west-1"
  register: ec2_key

- name: save private key
  copy:
    content: "{{ ec2_key.key.private_key }}" 
    dest: "./aws-private.pem" 
    mode: 0600
  when: ec2_key.changed

答案 1 :(得分:5)

Ansible documentation中的示例似乎显示了如何执行此操作:

# Creates a new ec2 key pair named `example` if not present, returns generated
# private key
- name: example ec2 key
  local_action:
    module: ec2_key
    name: example

# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example2 ec2 key
  local_action:
    module: ec2_key
    name: example2
    key_material: 'ssh-rsa AAAAxyz...== me@example.com'
    state: present

# Creates a new ec2 key pair named `example` if not present using provided key
# material
- name: example3 ec2 key
  local_action:
    module: ec2_key
    name: example3
    key_material: "{{ item }}"
  with_file: /path/to/public_key.id_rsa.pub

答案 2 :(得分:-1)

但是您无法保存生成的私钥,因此此方法不合适。使用命令模块并使用aws cli生成并保存pem文件中的私钥,而不是使用ec2_key模块。例如

- command: /usr/local/bin/aws ec2 create-key-pair --key-name keypair_name > ~/keypair_name.pem
  register: keypair