Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new key in Ansible using the ec2_key module?

Tags:

ansible

I don't know how to use the ec2_key module in Ansible. Can somebody please give me an example of how to create a new Key-Pair?

like image 457
SPM Avatar asked Dec 05 '22 05:12

SPM


2 Answers

working example:

- 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
like image 99
Arbab Nazar Avatar answered Dec 30 '22 11:12

Arbab Nazar


The examples in the Ansible documentation appear to show exactly how to do this:

# 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...== [email protected]'
    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
like image 36
Bruce P Avatar answered Dec 30 '22 11:12

Bruce P