PackerのAnsible RemoteでSSH ForwardAgentする
PackerのAnsible Remote ProvisionerでAMIをビルドしていますが、 SSH ForwardAgentできずにだいぶハマったので、備忘のためにメモしておきます。
やりたいこと
githubのプライベートリポジトリをansibleでcloneしたい。 公開鍵認証する必要あるが、private key はアップロードしたくないので、forward agent で解決したい。
なお、packerのバージョンは0.11.0です。
やったこと
packer.json
{ "variables": { "aws_access_key": "", "aws_secret_key": "" }, "builders": [{ "type": "amazon-ebs", "access_key": "{{user `aws_access_key`}}", "secret_key": "{{user `aws_secret_key`}}", "region": "ap-northeast-1", "source_ami": "ami-xxxxxxx", "instance_type": "t2.small", "ssh_username": "ec2-user" }], "provisioners": [{ "type": "ansible", "user" : "ec2-user", "sftp_command" : "/usr/libexec/openssh/sftp-server -e", "playbook_file": "ansible/playbook.yml", "ansible_env_vars": [ "ANSIBLE_HOST_KEY_CHECKING=False", "ANSIBLE_SSH_ARGS='-o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=60s'"] }] }
ここではANSIBLE_SSH_ARGS環境変数に -o ForwardAgent=yes をセットしています。
ansible.cfg
[defaults] sudo_flags=-HE
このオプションによりsudoでも環境変数を引き継ぐようになります。 sudoのmanには以下のように書かれています。
-E The -E (preserve environment) option will override the env_reset option in sudoers(5). It is only available when either the matching command has the SETENV tag or the setenv option is set in sudoers(5). sudo will return an error if the -E option is specified and the user does not have permission to preserve the environment.
これでANSIBLE_SSH_ARGSが有効になりました。
role
- name: git clone repository git: repo: 'git@github.com:organization/your-awesome-repo.git' dest: '/home/yourname/dir' accept_hostkey: yes version: master
あとはcloneするだけ。