Ananthu R V
Ananthu R V

Reputation: 458

How to copy a file to remote in `ansible_connection` local?

I am creating an azure vm using ansible using azure_rm_virtualmachine command. For this case the host is localhost (ansible_connection=local). I need to copy a ssh private key which is ansible-vault encrypted. How can i do this?

Here's what is already tried:

Anyone has any idea on how to approach this problem?

FYI: While creating the VM i have added my pub key there so i can access the machine

Upvotes: 0

Views: 677

Answers (1)

xenlo
xenlo

Reputation: 859

As far as I understand your use-case, you first create a new VM in Azure, and then you want to send a new private key on that fresh VM. I have two options for you.

Split in 2 plays

In the same playbook, you can have 2 different plays:

---
- name: Provisioning of my pretty little VM in Azure
  hosts: localhost
  vars: 
    my_vm_name: myprettyvm
    my_resource_group: myprettygroup
    …
  tasks:
  - name: Create the VM
    azure_rm_virtualmachine:
      resource_group: "{{ my_resource_group }}"
      name: "{{ my_vm_name }}"
    …

- name: Configure my pretty little VM with 
  hosts: myprettyvm
  vars:
    my_priv_key: !vault |
                 $ANSIBLE_VAULT;1.1;AES256
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  tasks:
  - name: Copy my private key
    copy:
      content: "{{ my_priv_key }}"
      dest: /root/.ssh/id_rsa

Delagate to localhost

Only one play in your playbook, but you delegate the provisioning task to localhost.

---
- name: Creation of my pretty little VM in Azure
  hosts: myprettyvm
  gather_facts: no
  vars: 
    my_vm_name: myprettyvm
    my_resource_group: myprettygroup
    …
    my_priv_key: !vault |
                 $ANSIBLE_VAULT;1.1;AES256
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
                 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
  tasks:
  - name: Create the VM
    azure_rm_virtualmachine:
      resource_group: "{{ my_resource_group }}"
      name: "{{ my_vm_name }}"
      …
    delegate_to: localhost

  - name: Copy my private key
    copy:
      content: "{{ my_priv_key }}"
      dest: /root/.ssh/id_rsa

Don't forget to set gather_facts to no as host is the VM that does not exist yet. So no fact available.

Upvotes: 1

Related Questions